Write Dynamically To PDF’s

The use of programming to write data to pdfs. This can be useful if the data that is on the pdf is linked to some kind of dynamic data (“Meaning the data is frequently updated). Can be useful for part data, that needs to be merged temporarily with order data. You can write this data automatically to the same pdf instead of printing out multiple pages of impertinent or irrelevant data. This allows an individual to save time, paper, and space, while accomplishing the same task as before.

import PyPDF2
import reportlab
from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
import csv
import os
import subprocess


#Get the files and fill string vars using csv or text files
def set_vars():
    cd = os.curdir
    print(cd)
    path = (cd  + "\Data\Variables.csv")
    path1 = (cd + "\Data\config.txt")
    path2 = (cd + "\Data\pdfs.txt")

    f = open(path1, "r")
    config = f.readlines()
    fpath1 = config[0]
    fpath2 = config[1]
    pos1 = config[2]
    pos2 = config[3]
    fontSize = config[4]
    cspace = config[5]
    wspace = config[6]
    exePath = config[7]

    with open(path) as csvfile:
        csvReader = csv.reader(csvfile, delimiter=",")
        array = []
        # array1 = []
        for row in csvReader:
            array.append(row)
            

    f = open(path2, "r")
    filenames = f.readlines()
    pdf_writer(fpath1, fpath2, exePath, int(pos1), int(pos2), int(cspace), int(wspace), int(fontSize), array, filenames) 

# Function to write data to the pdf's
def pdf_writer(fpath_1, fpath_2, exe, pos1, pos2, cspace, wspace, fontSize, vars_array = [], filenames = []):
    array = []
    for vars in vars_array:
        string = ' '.join(vars)
        print(string)
        array.append(string)

# Iterate over all files named in the csv or text file
    i = 0   
    for file in filenames: 
        fname = file
        fname = str(fname).rstrip('\n')
        fpath_2 = str(fpath_2).rstrip('\n')
        fpath_1 = str(fpath_1).rstrip('\n')


# This creates io buffer pdf and sets the pagesize
        packet = io.BytesIO()
        can = canvas.Canvas(packet, pagesize=letter)
        can.setFillColorRGB(1,0,0)
        can.setFont("Helvetica", fontSize)
        can.drawString(pos1, pos2, str(array[i]), mode=None, charSpace=cspace, direction=None, wordSpace=wspace)
        can.save()

#move to the beginning of the StringIO buffer
        packet.seek(0)
        
# create a new PDF with Reportlab
        new_pdf = PdfFileReader(packet)
# read your existing PDF
        existing_pdf = PdfFileReader(open(str(fpath_1 + fname + ".pdf"), "rb"))

# This section of code allows opens the pdf in a pdf reader #such as adobe acrobat to select a page if it has multiple #pages
        if existing_pdf.getNumPages() > 1:
            proc = subprocess.Popen([exe,'/n', fpath_1 + fname + ".pdf"])
            
            # print(proc.pid)
            
            import tkinter as tk
            from tkinter import simpledialog

            ROOT = tk.Tk()

            ROOT.withdraw()
            # the input dialog
            USER_INP = simpledialog.askinteger(title="Multiple Pages",
                                            prompt="Which Page Number?:")
                                            
            pageNumb = int(USER_INP)
            output = PdfFileWriter()

# add the "watermark" (which is the new pdf) on the existing 
# page
            page = existing_pdf.getPage(pageNumb)
            page.mergePage(new_pdf.getPage(0))
            output.addPage(page)

 # finally, write "output" to a real file
            outputStream = open(str(fpath_2 + fname + "_TEMP.pdf"), "wb")
            output.write(outputStream)
            outputStream.close()

            proc.terminate()

# This section will run directly in the event there is only one #page in pdf       
        output = PdfFileWriter()
        page = existing_pdf.getPage(0)
        page.mergePage(new_pdf.getPage(0))
        output.addPage(page)
# finally, write "output" to a real temporary file
        outputStream = open(str(fpath_2 + fname + "_TEMP.pdf"), "wb")
        output.write(outputStream)
        outputStream.close()
        i+=1

set_vars()

I am currently writing a working version of this for this website. It will be written using a javascript library, but it works much the same way. There are some minor differences with the JS version. I might upload a snippet of that code as well for viewing.

Leave a Reply

Your email address will not be published. Required fields are marked *