Skip to content

Instantly share code, notes, and snippets.

@rms1000watt
Last active March 29, 2024 11:24
Show Gist options
  • Save rms1000watt/177970ce9fb0970e765700f12695231d to your computer and use it in GitHub Desktop.
Save rms1000watt/177970ce9fb0970e765700f12695231d to your computer and use it in GitHub Desktop.
Python script to add JS to pdf so the pdf will print immediately when opened
# IE users need: https://get.adobe.com/reader/
from PyPDF2 import PdfFileWriter, PdfFileReader
output = PdfFileWriter()
ipdf = PdfFileReader(open('old.pdf', 'rb'))
for i in xrange(ipdf.getNumPages()):
page = ipdf.getPage(i)
output.addPage(page)
with open('new.pdf', 'wb') as f:
output.addJS("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
output.write(f)
@jissonv
Copy link

jissonv commented Jun 27, 2019

Good job. Worked in FireFox, Do have idea to how to do it in chrome?

@rms1000watt
Copy link
Author

@jissonv I thought this was built for chrome initially. Not sure what's changed since I authored this.. in like.. 2015. Curious why it doesn't work in chrome if you tried it.

@Hawary13
Copy link

Greate. I was trying to customize the solution to add a copy to clipboard function with file opening and it is not working. Any idea of how to do it?

@ishanluhani
Copy link

what does javascript does

@RaymonDev
Copy link

RaymonDev commented Jan 29, 2023

Updated version for python 3.x

from PyPDF2 import PdfWriter, PdfReader

output = PdfWriter()
ipdf = PdfReader(open('old.pdf', 'rb'))

for i in range(len(ipdf.pages)):
    page = ipdf.pages[i]
    output.add_page(page)

with open('new.pdf', 'wb') as f:
    output.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
    output.write(f)

@khaledesmail
Copy link

Hi @RaymonDev,
This not working for Chrome, the PDF is opened without any action
what is the expected output for this.

@RaymonDev
Copy link

I honestly have no idea. I just translated the code to 3.x, working on it though!!

@khaledesmail
Copy link

Ok, Did you try it in Chrome ?

@RaymonDev
Copy link

Yes, still not working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment