Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove external dependcy on pdftk #75

Open
canismarko opened this issue Jun 16, 2020 · 3 comments
Open

Remove external dependcy on pdftk #75

canismarko opened this issue Jun 16, 2020 · 3 comments

Comments

@canismarko
Copy link
Owner

Currently, filling in the PDF forms is done using pdftk. It would be nice if we could remove this dependency and use only pypi packages. This issue in the PyPDF2 package my help with this: py-pdf/pypdf#355 (comment)

@ale-rt
Copy link

ale-rt commented Feb 26, 2021

LOL I had the same issue, this is what I came up with:

#!/usr/bin/env python3
from PyPDF4.generic import NameObject
from PyPDF4.generic import TextStringObject
from PyPDF4.pdf import PdfFileReader
from PyPDF4.pdf import PdfFileWriter

import random
import sys

reader = PdfFileReader(sys.argv[1])

writer = PdfFileWriter()
# Try to "clone" the original one (note the library has cloneDocumentFromReader)
# but the render pdf is blank
writer.appendPagesFromReader(reader)
writer._info = reader.trailer["/Info"]
reader_trailer = reader.trailer["/Root"]
writer._root_object.update(
    {
        key: reader_trailer[key]
        for key in reader_trailer
        if key in ("/AcroForm", "/Lang", "/MarkInfo")
    }
)

page = writer.getPage(0)

params = {"Foo": "Bar"}

# Inspired by updatePageFormFieldValues but also handle checkboxes
for annot in page["/Annots"]:
    writer_annot = annot.getObject()
    field = writer_annot["/T"]
    if writer_annot["/FT"] == "/Btn":
        value = params.get(field, random.getrandbits(1))
        if value:
            writer_annot.update(
                {
                    NameObject("/AS"): NameObject("/On"),
                    NameObject("/V"): NameObject("/On"),
                }
            )
    elif writer_annot["/FT"] == "/Tx":
        value = params.get(field, field)
        writer_annot.update(
            {
                NameObject("/V"): TextStringObject(value),
            }
        )

with open(sys.argv[2], "wb") as f:
    writer.write(f)

https://stackoverflow.com/a/66388344/646005

@canismarko
Copy link
Owner Author

Thanks. Unfortunately, I don't have the bandwidth to work on this right now but hopefully that SO post will be useful when I (or someone else) do.

@bw-mutley
Copy link
Contributor

I've just made a PR to use @matsavage latex package, take a look when you can.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants