Skip to content

Instantly share code, notes, and snippets.

@SalvaJ
Last active January 21, 2018 09:59
Show Gist options
  • Save SalvaJ/ae9d8d20d7e88b3fa717 to your computer and use it in GitHub Desktop.
Save SalvaJ/ae9d8d20d7e88b3fa717 to your computer and use it in GitHub Desktop.
To unlock a pdf file using 'gs' in linux shell and convert the content to text
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This code is for being used with pdfminer last version (Python 2.x)
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO
def convert_pdf_to_txt(path):
"""
function from http://stackoverflow.com/questions/5725278/
python-help-using-pdfminer-as-a-library
"""
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = file(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
fp.close()
device.close()
str = retstr.getvalue()
retstr.close()
return str
print(convert_pdf_to_txt("/home/salvaj/Documentos/BOE-A-2014-8133.pdf"))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This gist code is for being used with pdfminer3k package (Python 3.x)
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from io import StringIO
def convert_pdf(path):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, laparams=laparams)
fp = open(path, 'rb')
process_pdf(rsrcmgr, device, fp)
fp.close()
device.close()
str = retstr.getvalue()
retstr.close()
return str
print(convert_pdf(r".\notas_simples\nota_simple_ul.pdf"))
C:\> gswin32c -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sFONTPATH=%windir%/fonts;xfonts;. -sPDFPassword= -dPDFSETTINGS=/prepress -dPassThroughJPEGImages=true -sOutputFile=OUTPUT.pdf INPUT.pdf
user@host~/Documents$ gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=unencrypted.pdf -c .setpdfwrite -f encrypted.pdf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment