首页 文章

如何使用PyPDF2获得Pdf方向

提问于
浏览
0

我正在使用Python / Django .
PyPDF2读取我当前的pdf .

我想阅读我已保存的pdf并获取pdf中单页的方向 .

我希望能够确定页面是横向还是纵向 .

tempoutpdffilelocation =  settings.TEMPLATES_ROOT + nameOfFinalPdf
pageOrientation = pageToEdit.mediaBox
pdfOrientation = PdfFileReader(file(temppdffilelocation, "rb"))
# tempPdfOrientationPage = pdfOrientation.getPage(numberOfPageToEdit).mediaBox
print("existing pdf width: ")
# print(existing_pdf.getPage(numberOfPageToEdit).getWidth)
# print("get page size with rotation")
# print(tempPdfOrientationPage.getPageSizeWithRotation) 

existing_pdf = pdfOrientation.getPage(numberOfPageToEdit).mediaBox
# print(pageOrientation)
if pageOrientation.getUpperRight_x() - pageOrientation.getUpperLeft_x() > pageOrientation.getUpperRight_y() - pageOrientation.getLowerRight_y():
  print('Landscape')
  print(pageOrientation)
  # print(pdfOrientation.getWidth())
else:
  print('Portrait')
  print(pageOrientation)
  # print(pdfOrientation.getWidth())
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)

最后一行根据我当前的pdf设置pagesize = letter我想要确定的内容 .
这是我的进口:

from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, landscape
import urllib

我've tried pyPdf .mediaBox but that always returns the same value of the expected file size, not the actual size. And pyPdf is outdated. As you can see I' ve也试过getWidth和withRotation .
我认为PyPDF2 PdfFileReader有一种简单的方法来确定所选对象的方向 .

任何帮助表示赞赏 . 谢谢 .

3 回答

  • 2

    我只使用了页面的“ /Rotate ”属性:

    OrientationDegrees = pdf.getPage(numberOfPageToEdit).get('/Rotate')
    

    它可以是 0, 90, 180, 270None

  • 0

    您可以使用以下代码段检测它:

    from PyPDF2  import PdfFileReader
    
    pdf = PdfFileReader(file('example.pdf'))
    page = pdf.getPage(0).mediaBox
    if page.getUpperRight_x() - page.getUpperLeft_x() > page.getUpperRight_y() - 
    page.getLowerRight_y():
        print('Landscape')
    else:
        print('Portrait')
    
  • 0

    这个工作,经过充分测试:

    import PyPDF2
    from PyPDF2  import PdfFileReader
    
    pdf = PdfFileReader(open('YourPDFname.pdf', 'rb'))
    page = pdf.getPage(0).mediaBox
    
    if page.getUpperRight_x() - page.getUpperLeft_x() > page.getUpperRight_y() - 
    page.getLowerRight_y():
        print('Landscape')
    else:
        print('Portrait')
    

相关问题