use ghostscript to create output file(s) from the PDF
962072
def gswrite(self, fn=None, device='jpeg', res=600, alpha=4, quality=90, gs=None):
        ""
        gs = (gs or self.gs or os.environ.get('gs') or 'gs')
        # count the number of pages
        if fn is None: 
            fn = os.path.splitext(self.fn)[0] + DEVICE_EXTENSIONS[device]
        fn = File(fn=fn).fn     # normalize path
        if not os.path.exists(os.path.dirname(fn)):
            os.makedirs(os.path.dirname(fn))
        log.debug("PDF.gswrite():\n\tself.fn = %s\n\tout fn = %s" % (self.fn, fn))
        if os.path.splitext(self.fn)[-1].lower()=='.pdf':
            cmd = [gs, '-q', '-dNODISPLAY', '-c', 
                    "(%s) (r) file runpdfbegin pdfpagecount = quit" % self.fn]
            log.debug(cmd)
            out = subprocess.check_output(cmd).decode('utf-8').strip()
            if out=='': out = '1'
            pages = int(out)
            log.debug("%d page(s)" % pages)
        else:
            pages = 1
        if pages > 1:
            # add a counter to the filename, which tells gs to create a file for every page in the input
            fb, ext = os.path.splitext(fn)
            n = len(re.split('.', str(pages))) - 1
            counter = "-%%0%dd" % n
            fn = fb + counter + ext

            # remove any existing output filenames that match the pattern
            for existingfn in glob(fb+'*'+ext):
                log.debug("REMOVING %s" % existingfn)
                os.remove(existingfn)

        callargs = [gs, '-q', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dUseCropBox',
                    '-sDEVICE=%s' % device, '-r%d' % res]
        if device=='jpeg': 
            callargs += ['-dJPEGQ=%d' % quality]
        if 'png' in device or 'jpeg' in device or 'tiff' in device: 
            callargs += [
                '-dTextAlphaBits=%d' % alpha,
                '-dGraphicsAlphaBits=%d' % alpha]
        callargs += ['-sOutputFile=%s' % fn, self.fn]
        try:
            log.debug(callargs)
            subprocess.check_output(callargs)
        except subprocess.CalledProcessError as e:
            log.error(callargs)
            log.error(str(e.output, 'utf-8'))
        fns = sorted(glob(re.sub('%\d+d','*', fn)))
        log.debug('\n\t'+'\n\t'.join(fns))
        return fns
1119792
function(err, results) {
      var paperFormat = paperSize.format || "A4";
      var paperOrientation = paperSize.orientation || "portrait";
      var paperBorder = paperSize.border || "1cm";
      var paperWidth  = paperSize.width || 'false';
      var paperHeight = paperSize.height || 'false';
      var renderDelay = paperSize.delay || 500;

      /* All necessary files have been created.
       * Construct arguments and create a new phantom process.
       */
      var childArgs = [
        path.join(__dirname, "phantom-script.js"),
        results[0],
        results[1],
        results[2],
        results[3],
        results[4],
        paperFormat,
        paperOrientation,
        paperBorder,
        paperWidth,
        paperHeight,
        renderDelay,
        runningsArgs
      ];

      childProcess.execFile(phantom.path, childArgs, function(err, stdout, stderr) {
        var opPointer = new PDFResult(err, results[1]);

        if (typeof callback === "function") {
          callback(err, opPointer);
        }
      });
    }
294504
def create_parser():
    

    parser = argparse.ArgumentParser(
        description='Extract structured data from PDF files and save to CSV or JSON.'
    )

    parser.add_argument(
        '--input-reader',
        choices=input_mapping.keys(),
        default='pdftotext',
        help='Choose text extraction function. Default: pdftotext',
    )

    parser.add_argument(
        '--output-format',
        choices=output_mapping.keys(),
        default='none',
        help='Choose output format. Default: none',
    )

    parser.add_argument(
        '--output-name',
        '-o',
        dest='output_name',
        default='invoices-output',
        help='Custom name for output file. Extension is added based on chosen format.',
    )

    parser.add_argument(
        '--debug', dest='debug', action='store_true', help='Enable debug information.'
    )

    parser.add_argument(
        '--copy', '-c', dest='copy', help='Copy and rename processed PDFs to specified folder.'
    )

    parser.add_argument(
        '--move', '-m', dest='move', help='Move and rename processed PDFs to specified folder.'
    )

    parser.add_argument(
        '--filename-format',
        dest='filename',
        default="{date} {invoice_number} {desc}.pdf",
        help='Filename format to use when moving or copying processed PDFs.'
             'Default: "{date} {invoice_number} {desc}.pdf"',
    )

    parser.add_argument(
        '--template-folder',
        '-t',
        dest='template_folder',
        help='Folder containing invoice templates in yml file. Always adds built-in templates.',
    )

    parser.add_argument(
        '--exclude-built-in-templates',
        dest='exclude_built_in_templates',
        default=False,
        help='Ignore built-in templates.',
        action="store_true",
    )

    parser.add_argument(
        'input_files', type=argparse.FileType('r'), nargs='+', help='File or directory to analyze.'
    )

    return parser
947814
def output_pdf(html, filename)
      args = command(filename)
      invoke = args.join(' ')

      IO.popen(invoke, "wb+") do |pdf|
        pdf.puts(html)
        pdf.close_write
        pdf.gets(nil)
      end
    end
140261
def save_pdf(opts = {})
      range = Args::CardRange.new(opts[:range], deck_size: size)
      sheet = Args::Sheet.new(custom_colors, { file: 'output.pdf' }).load!(opts, expand_by: size, layout: layout, dpi: dpi)
      sprue_file = Args::SprueFile.new.load!(opts, expand_by: size)

      if sprue_file.sprue.nil?
        Graphics::SavePDF.new(self).render_pdf(range, sheet)
      else
        tmpl = Sprue.load sprue_file.sprue, dpi
        Graphics::SaveSpruePDF.
          new(self, tmpl, sheet).
          render_sheet(range)
      end
    end
308716
private TessResultRenderer createRenderers(String outputbase, List<RenderedFormat> formats) {
        TessResultRenderer renderer = null;

        for (RenderedFormat format : formats) {
            switch (format) {
                case TEXT:
                    if (renderer == null) {
                        renderer = api.TessTextRendererCreate(outputbase);
                    } else {
                        api.TessResultRendererInsert(renderer, api.TessTextRendererCreate(outputbase));
                    }
                    break;
                case HOCR:
                    if (renderer == null) {
                        renderer = api.TessHOcrRendererCreate(outputbase);
                    } else {
                        api.TessResultRendererInsert(renderer, api.TessHOcrRendererCreate(outputbase));
                    }
                    break;
                case PDF:
                    String dataPath = api.TessBaseAPIGetDatapath(handle);
                    boolean textonly = String.valueOf(TRUE).equals(prop.getProperty("textonly_pdf"));
                    if (renderer == null) {
                        renderer = api.TessPDFRendererCreate(outputbase, dataPath, textonly ? TRUE : FALSE);
                    } else {
                        api.TessResultRendererInsert(renderer, api.TessPDFRendererCreate(outputbase, dataPath, textonly ? TRUE : FALSE));
                    }
                    break;
                case BOX:
                    if (renderer == null) {
                        renderer = api.TessBoxTextRendererCreate(outputbase);
                    } else {
                        api.TessResultRendererInsert(renderer, api.TessBoxTextRendererCreate(outputbase));
                    }
                    break;
                case UNLV:
                    if (renderer == null) {
                        renderer = api.TessUnlvRendererCreate(outputbase);
                    } else {
                        api.TessResultRendererInsert(renderer, api.TessUnlvRendererCreate(outputbase));
                    }
                    break;
                case ALTO:
                    if (renderer == null) {
                        renderer = api.TessAltoRendererCreate(outputbase);
                    } else {
                        api.TessResultRendererInsert(renderer, api.TessAltoRendererCreate(outputbase));
                    }
                    break;
                case TSV:
                    if (renderer == null) {
                        renderer = api.TessTsvRendererCreate(outputbase);
                    } else {
                        api.TessResultRendererInsert(renderer, api.TessTsvRendererCreate(outputbase));
                    }
                    break;
                case LSTMBOX:
                    if (renderer == null) {
                        renderer = api.TessLSTMBoxRendererCreate(outputbase);
                    } else {
                        api.TessResultRendererInsert(renderer, api.TessLSTMBoxRendererCreate(outputbase));
                    }
                    break;
                case WORDSTRBOX:
                    if (renderer == null) {
                        renderer = api.TessWordStrBoxRendererCreate(outputbase);
                    } else {
                        api.TessResultRendererInsert(renderer, api.TessWordStrBoxRendererCreate(outputbase));
                    }
                    break;
            }
        }

        return renderer;
    }
300345
def write_pdf(self, html):
        
        try:
            f = tempfile.NamedTemporaryFile(delete=False, suffix='.html')
            f.write(html.encode('utf_8', 'xmlcharrefreplace'))
            f.close()
        except Exception:
            raise IOError(u"Unable to create temporary file, aborting")

        dummy_fh = open(os.path.devnull, 'w')

        try:
            command = ["prince", f.name, "-o", self.destination_file]

            Popen(command, stderr=dummy_fh).communicate()
        except Exception:
            raise EnvironmentError(u"Unable to generate PDF file using "
                                    "prince. Is it installed and available?")
        finally:
            dummy_fh.close()
907261
function writeFile(output, filePath, content) {
    var rootFolder = output.getRoot();
    filePath = path.join(rootFolder, filePath);

    return fs.ensureFile(filePath)
    .then(function() {
        return fs.writeFile(filePath, content);
    })
    .thenResolve(output);
}
489033
def pdf_from_string(string, output_file = '-')
      with_timeout do
        pdf = initialize_pdf_from_string(string, output_file, {:output_to_log_file => false})
        pdf.close_write
        result = pdf.gets(nil)
        pdf.close_read
        result.force_encoding('BINARY') if RUBY_VERSION >= "1.9"

        result
      end
    end
525070
def create(self, options=None):
        """"""
        if options is None:
            raise ValueError("Please pass in an options dict")

        if not _has_content(options):
            raise NoContentError("must supply 'document_content' or 'document_url'")

        default_options = {
            "name": "default",
            "document_type": "pdf",
            "test": False,
            "async": False,
            "raise_exception_on_failure": False,
        }
        options = dict(list(default_options.items()) + list(options.items()))
        raise_exception_on_failure = options.pop("raise_exception_on_failure")
        query = {"user_credentials": self.api_key}
        if options["async"]:
            query["output"] = "json"

        resp = requests.post(
            "%sdocs" % (self._url), json=options, params=query, timeout=self._timeout
        )

        if raise_exception_on_failure and resp.status_code != 200:
            raise DocumentCreationFailure(resp.content, resp.status_code)

        if options["async"]:
            return json.loads(resp.content.decode("utf-8"))
        else:
            return resp
1296244
def add_pdf(self, post_data):
        '''
        
        '''

        img_entity = self.request.files['file'][0]
        img_desc = post_data['desc']
        filename = img_entity["filename"]

        if filename and allowed_file_pdf(filename):
            pass
        else:
            return False

        _, hou = os.path.splitext(filename)
        signature = str(uuid.uuid1())
        outfilename = '{0}{1}'.format(signature, hou)
        outpath = 'static/upload/{0}'.format(signature[:2])
        if os.path.exists(outpath):
            pass
        else:
            os.makedirs(outpath)
        with open(os.path.join(outpath, outfilename), "wb") as fout:
            fout.write(img_entity["body"])

        sig_save = os.path.join(signature[:2], signature)
        path_save = os.path.join(signature[:2], outfilename)
        create_pdf = MEntity.create_entity(signature, path_save, img_desc,
                                           kind=post_data['kind'] if 'kind' in post_data else '2')
        if self.entity_ajax == False:
            self.redirect('/entity/{0}{1}'.format(sig_save, hou.lower()))
        else:
            if create_pdf:
                output = {'path_save': path_save}
            else:
                output = {'path_save': ''}
            return json.dump(output, self)
625387
function(pages, callback) {
      // Use eachSeries to make sure that conversion has done page by page
      async.eachSeries(pages, function(page, callbackmap) {
        var inputStream = fs.createReadStream(input);
        var outputFile = options.outputdir + options.outputname + '_' + page + '.' + options.type;

        convertPdf2Img(inputStream, outputFile, parseInt(page), function(error, result) {
          if (error) {
            return callbackmap(error);
          }

          stdout.push(result);
          return callbackmap(error, result);
        });
      }, function(e) {
        if (e) callback(e);

        return callback(null, {
          result: 'success',
          message: stdout
        });
      });
    }
1239759
def get_bounding_box_list_ghostscript(input_doc_fname, res_x, res_y, full_page_box):
    """"""

    if not gs_executable: init_and_test_gs_executable(exit_on_fail=True)
    res = str(res_x) + "x" + str(res_y)
    box_arg = "-dUseMediaBox" # should be default, but set anyway
    if "c" in full_page_box: box_arg = "-dUseCropBox"
    if "t" in full_page_box: box_arg = "-dUseTrimBox"
    if "a" in full_page_box: box_arg = "-dUseArtBox"
    if "b" in full_page_box: box_arg = "-dUseBleedBox" # may not be defined in gs
    gs_run_command = [gs_executable, "-dSAFER", "-dNOPAUSE", "-dBATCH", "-sDEVICE=bbox",
                    box_arg, "-r"+res, input_doc_fname]
    # Set printOutput to True for debugging or extra-verbose with Ghostscript's output.
    # Note Ghostscript writes the data to stderr, so the command below must capture it.
    try:
        gs_output = get_external_subprocess_output(gs_run_command,
                          print_output=False, indent_string="   ", env=gs_environment)
    except UnicodeDecodeError:
        print("\nError in pdfCropMargins:  In attempting to get the bounding boxes"
              "\nGhostscript encountered characters which cannot be decoded by the"
              "\n'utf-8' codec.",
              file=sys.stderr)
        cleanup_and_exit(1)

    bounding_box_list = []
    for line in gs_output:
        split_line = line.split()
        if split_line and split_line[0] == r"%%HiResBoundingBox:":
            del split_line[0]
            if len(split_line) != 4:
                print("\nWarning from pdfCropMargins: Ignoring this unparsable line"
                      "\nwhen finding the bounding boxes with Ghostscript:",
                      line, "\n", file=sys.stderr)
                continue
            # Note gs reports values in order left, bottom, right, top,
            # i.e., lower left point followed by top right point.
            bounding_box_list.append([float(split_line[0]),
                                    float(split_line[1]),
                                    float(split_line[2]),
                                    float(split_line[3])])

    if not bounding_box_list:
        print("\nError in pdfCropMargins: Ghostscript failed to find any bounding"
              "\nboxes in the document.", file=sys.stderr)
        cleanup_and_exit(1)
    return bounding_box_list
680413
public static void mergePdf(File[] inputPdfFiles, File outputPdfFile) {
        //get Ghostscript instance
        Ghostscript gs = Ghostscript.getInstance();

        //prepare Ghostscript interpreter parameters
        //refer to Ghostscript documentation for parameter usage
        //gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -sOutputFile=out.pdf in1.pdf in2.pdf in3.pdf
        List<String> gsArgs = new ArrayList<String>();
        gsArgs.add("-gs");
        gsArgs.add("-dNOPAUSE");
        gsArgs.add("-dQUIET");
        gsArgs.add("-dBATCH");
        gsArgs.add("-sDEVICE=pdfwrite");
        gsArgs.add("-sOutputFile=" + outputPdfFile.getPath());

        for (File inputPdfFile : inputPdfFiles) {
            gsArgs.add(inputPdfFile.getPath());
        }

        //execute and exit interpreter
        try {
            synchronized (gs) {
                gs.initialize(gsArgs.toArray(new String[0]));
                gs.exit();
            }
        } catch (UnsatisfiedLinkError e) {
            logger.error(e.getMessage());
            throw new RuntimeException(getMessage(e.getMessage()));
        } catch (NoClassDefFoundError e) {
            logger.error(e.getMessage());
            throw new RuntimeException(getMessage(e.getMessage()));
        } catch (GhostscriptException e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            //delete interpreter instance (safer)
            try {
                Ghostscript.deleteInstance();
            } catch (GhostscriptException e) {
                //nothing
            }
        }
    }
505044
def write_pdf_files(args, infilenames, outfilename):
    
    if not outfilename.endswith('.pdf'):
        outfilename = outfilename + '.pdf'
    outfilename = overwrite_file_check(args, outfilename)

    options = {}
    try:
        if args['multiple']:
            # Multiple files are written one at a time, so infilenames will
            # never contain more than one file here
            infilename = infilenames[0]
            if not args['quiet']:
                print('Attempting to write to {0}.'.format(outfilename))
            else:
                options['quiet'] = None

            if args['xpath']:
                # Process HTML with XPath before writing
                html = parse_html(read_files(infilename), args['xpath'])
                if isinstance(html, list):
                    if isinstance(html[0], str):
                        pk.from_string('\n'.join(html), outfilename,
                                       options=options)
                    else:
                        pk.from_string('\n'.join(lh.tostring(x) for x in html),
                                       outfilename, options=options)
                elif isinstance(html, str):
                    pk.from_string(html, outfilename, options=options)
                else:
                    pk.from_string(lh.tostring(html), outfilename,
                                   options=options)
            else:
                pk.from_file(infilename, outfilename, options=options)
        elif args['single']:
            if not args['quiet']:
                print('Attempting to write {0} page(s) to {1}.'
                      .format(len(infilenames), outfilename))
            else:
                options['quiet'] = None

            if args['xpath']:
                # Process HTML with XPath before writing
                html = parse_html(read_files(infilenames), args['xpath'])
                if isinstance(html, list):
                    if isinstance(html[0], str):
                        pk.from_string('\n'.join(html), outfilename,
                                       options=options)
                    else:
                        pk.from_string('\n'.join(lh.tostring(x) for x in html),
                                       outfilename, options=options)
                elif isinstance(html, str):
                    pk.from_string(html, outfilename, options=options)
                else:
                    pk.from_string(lh.tostring(html), outfilename,
                                   options=options)
            else:
                pk.from_file(infilenames, outfilename, options=options)
        return True
    except (OSError, IOError) as err:
        sys.stderr.write('An error occurred while writing {0}:\n{1}'
                         .format(outfilename, str(err)))
        return False
615592
def notescan_main(options):

    ''''''

    filenames = get_filenames(options)

    outputs = []

    do_global = options.global_palette and len(filenames) > 1

    if do_global:
        filenames, palette = get_global_palette(filenames, options)

    do_postprocess = bool(options.postprocess_cmd)

    for input_filename in filenames:

        img, dpi = load(input_filename)
        if img is None:
            continue

        output_filename = '{}{:04d}.png'.format(
            options.basename, len(outputs))

        if not options.quiet:
            print('opened', input_filename)

        if not do_global:
            samples = sample_pixels(img, options)
            palette = get_palette(samples, options)

        labels = apply_palette(img, palette, options)

        save(output_filename, labels, palette, dpi, options)

        if do_postprocess:
            post_filename = postprocess(output_filename, options)
            if post_filename:
                output_filename = post_filename
            else:
                do_postprocess = False

        outputs.append(output_filename)

        if not options.quiet:
            print('  done\n')

    emit_pdf(outputs, options)
341227
def export_pdf(self, filename):
        
        self.make_request(
            raw_result=True,
            resource='export',
            filename=filename, 
            headers = {'accept': 'application/pdf'})