ihmeuw-demographics / demUtils

Utility functions for working with demographic data and estimates.
https://ihmeuw-demographics.github.io/demUtils
BSD 3-Clause "New" or "Revised" License
0 stars 2 forks source link

Helper function to combine pdfs #11

Closed chacalle closed 4 years ago

chacalle commented 4 years ago

Use PyPDF2 and reticulate to combine files

krpaulson commented 4 years ago

Something like this.

Add to inst/python: https://r-pkgs.org/inst.html#inst-other-langs And write wrapper function in R with reticulate: https://blog.rstudio.com/2018/03/26/reticulate-r-interface-to-python/

def merge_pdf(output_path, input_paths):
  """Combine PDFs into a single file
    Parameters
    ----------
    output_path : str
        Filepath for combined PDF output
    input_paths : str
        List of input PDFs in order to be combined
    Returns
    -------
    Nothing. Combined PDF saved to `output_path`.
  """

    if os.path.exists(output_path):
        os.remove(output_path)

    pdf_writer = PdfFileWriter()

    for path in input_paths:
        pdf_reader = PdfFileReader(path)
        for page in range(pdf_reader.getNumPages()):
            pdf_writer.addPage(pdf_reader.getPage(page))

    with open(output_path, 'wb') as fh:
        pdf_writer.write(fh)