Python处理PDF及生成多层PDF实例代码
Python提供了众多的PDF支持库,本文是在Python3环境下,试用了两个库来完成PDF的生成的功能。PyPDF对于读取PDF支持较好,但是没找到生成多层PDF的方法。Reportlab看起来更成熟,能够利用Canvas很方便的生成多层PDF,这样就能够实现图片扫描上来的内容也可以进行内容搜索的目标。
Reportlab
生成双层PDF
双层PDF应用PDF中的Canvas概念,先画文字,最后将图片画上去,这样就是两层的PDF。
importos
#importurllib2
importtime
fromreportlabimportplatypus
fromreportlab.lib.pagesizesimportletter
fromreportlab.lib.unitsimportinch
fromreportlab.platypusimportSimpleDocTemplate,Image
fromreportlab.pdfgenimportcanvas
image_file="./42.png"
#UseCanvastogeneratepdf
c=canvas.Canvas('reportlab_canvas.pdf',pagesize=letter)
width,height=letter
c.setFillColorRGB(0,0.77,0.77)
#sayhello(noteafterrotatetheycoordneedstobenegative!)
c.drawString(3*inch,3*inch,"HelloWorld")
c.drawImage(image_file,0,0)
c.showPage()
c.save()
PyPDF2
读取PDF
fromPyPDF2importPdfFileWriter,PdfFileReader
output=PdfFileWriter()
input1=PdfFileReader(open("jquery.pdf","rb"))
#printdocumentinfo
print(input1.getDocumentInfo())
#printhowmanypagesinput1has:
print("pdf_document.pdfhas%dpages."%input1.getNumPages())
#printpagecontent
page_content=input1.getPage(0).extractText()
print(page_content)
#addpage1frominput1tooutputdocument,unchanged
output.addPage(input1.getPage(0))
#addpage2frominput1,butrotatedclockwise90degrees
output.addPage(input1.getPage(1).rotateClockwise(90))
#finally,write"output"todocument-output.pdf
outputStream=open("PyPDF2-output.pdf","wb")
output.write(outputStream)
但是PyPDF获取PDF内容有很多问题,可以看这个问题列表。文档中也有说明。
|extractText(self)|##|#Locatealltextdrawingcommands,intheordertheyareprovidedinthe|#contentstream,andextractthetext.ThisworkswellforsomePDF|#files,butpoorlyforothers,dependingonthegeneratorused.Thiswill|#berefinedinthefuture.Donotrelyontheorderoftextcomingoutof|#thisfunction,asitwillchangeifthisfunctionismademore|#sophisticated.|# |#Stability:Addedinv1.7,willexistforallfuturev1.xreleases.May|#beoverhauledtoprovidemoreorderedtextinthefuture.|#@returnaunicodestringobject
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。