development

파이썬에서 PDF 파일을 만드는 방법

big-blog 2020. 6. 6. 07:58
반응형

파이썬에서 PDF 파일을 만드는 방법


사용자로부터 일부 이미지를 가져온 다음 이러한 이미지가 모두 포함 된 PDF 파일을 만드는 프로젝트를 진행 중입니다.

파이썬에서 이것을 할 수있는 방법이나 도구가 있습니까? 예를 들어 image1 + image 2 + image 3-> PDF 파일에서 PDF 파일 (또는 eps, ps)을 만들려면?


pyPdf 제안 합니다 . 정말 잘 작동합니다. 또한 얼마 전에 블로그 게시물을 작성했습니다 . 여기에서 찾을 수 있습니다 .


이 페이지의 힌트를 따른 후의 경험입니다.

  1. pyPDF는 이미지를 파일에 포함 할 수 없습니다. 분할 및 병합 만 가능합니다. (출처 : Ctrl + F 문서 페이지를 통해 ) PDF에 포함되지 않은 이미지가있는 경우에는 좋지 않습니다.

  2. pyPDF2 에는 pyPDF 위에 추가 문서가없는 것 같습니다.

  3. ReportLab은 매우 광범위합니다. ( Userguide ) 그러나 약간의 Ctrl + F와 소스를 통해 grepping하면 다음과 같은 결과를 얻 습니다.

필요한 것은 PDF로 많은 이미지를 가져 와서 이미지를보고 인쇄하는 방법을 확인할 수 있습니다. 위의 목표는 그 목표를 달성하기에 충분합니다.

ReportLab은 훌륭하지만 위와 같은 helloworld를 문서에 눈에 띄게 포함하면 도움이 될 것입니다.


나는 Pdfkit을 제안 한다 . (설치 안내서 )

html 파일에서 pdf를 만듭니다. Python Pyramid 스택에서 2 단계로 pdf를 만들도록 선택했습니다.

  1. 원하는 스타일과 마크 업이있는 mako 템플릿으로 서버 측 렌더링 pdf 문서
  2. pdfkit.from_string(...)렌더링 된 html을 매개 변수로 전달하여 메소드 실행

이렇게하면 스타일과 이미지가 지원되는 PDF 문서를 얻을 수 있습니다.

다음과 같이 설치할 수 있습니다.

  • 핍 사용

    pip install pdfkit

  • 또한 wkhtmltopdf ( Ubuntu에 ) 를 설치해야합니다 .

이것을 시도 하거나 (Python-for-PDF-Generation) pdf로 인쇄를 지원하는 PyQt 를 시도 할 수 있습니다 .

PDF 생성 용 Python PDF

(Portable Document Format)를 사용하면 모든 플랫폼에서 똑같이 보이는 문서를 만들 수 있습니다. 그러나 때로는 PDF 문서를 동적으로 생성해야하는 경우도 있습니다. 다행히도 도움이 될 수있는 라이브러리가 있습니다. 이 기사에서는 Python에 대한 기사 중 하나를 살펴 봅니다.

http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/#whoCFCPh3TAks368.99 에서 자세히 알아보십시오 .


PyQt 에서이 작업을 꽤 많이 수행했으며 매우 잘 작동합니다. Qt는 이미지, 글꼴, 스타일 등을 광범위하게 지원하며 모든 것을 pdf 문서로 작성할 수 있습니다.


matplotlib에는 그래픽, 텍스트 및 기타 객체를 pdf 문서로 직렬화하는 기능이 있다고 생각합니다.


내가 사용 rst2pdf을 나는 HTML보다 RST 더 잘 알고 있기 때문에, PDF 파일을 만들 수 있습니다. 거의 모든 종류의 래스터 또는 벡터 이미지 임베딩을 지원합니다.

reportlab 이 필요 하지만 reportlab이 사용하기에 너무 간단하지 않다는 것을 알았습니다 (적어도 나를 위해).


fpdf는 파이썬입니다. 그리고 자주 사용됩니다. PyPI / pip 검색을 참조하십시오. 그러나 pyfpdf에서 fpdf로 이름이 바뀌었을 수 있습니다. 기능에서 : PNG, GIF 및 JPG 지원 (투명도 및 알파 채널 포함)


다음은 표준 패키지에서만 작동하는 솔루션입니다. matplotlib그림을 PDF로 저장하는 PDF 백엔드가 있습니다. 각 서브 플롯이 이미지 중 하나 인 서브 플롯으로 그림을 만들 수 있습니다. 당신은 그림을 엉망으로 만들 수 있습니다 : 타이틀 추가, 포지션 플레이 등. 그림이 완성되면 PDF로 저장하십시오. 호출 할 때마다 savefig다른 PDF 페이지가 작성됩니다.

아래 예는 1 페이지와 2 페이지에 2 개의 이미지를 나란히 표시합니다.

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from scipy.misc import imread
import os
import numpy as np

files = [ "Column0_Line16.jpg", "Column0_Line47.jpg" ]
def plotImage(f):
    folder = "C:/temp/"
    im = imread(os.path.join(folder, f)).astype(np.float32) / 255
    plt.imshow(im)
    a = plt.gca()
    a.get_xaxis().set_visible(False) # We don't need axis ticks
    a.get_yaxis().set_visible(False)

pp = PdfPages("c:/temp/page1.pdf")
plt.subplot(121)
plotImage(files[0])
plt.subplot(122)
plotImage(files[1])
pp.savefig(plt.gcf()) # This generates page 1
pp.savefig(plt.gcf()) # This generates page 2
pp.close()

실제로 xhtml2pdf http://flask.pocoo.org/snippets/68/를 시도 할 수 있습니다


It depends on what format your image files are in, but for a project here at work I used the tiff2pdf tool in LibTIFF from RemoteSensing.org. Basically just used subprocess to call tiff2pdf.exe with the appropriate argument to read the kind of tiff I had and output the kind of pdf I wanted. If they aren't tiffs you could probably convert them to tiffs using PIL, or maybe find a tool more specific to your image type (or more generic if the images will be diverse) like ReportLab mentioned above.


rinohtype supports embedding PDF, PNG and JPEG images (natively) and other bitmap formats (when Pillow is installed).

(Full disclosure: I am the author of rinohtype)


If you are familiar with LaTex you might want to consider pylatex

One of the advantages of pylatex is that it is easy to control the image quality. The images in your pdf will be of the same quality as the original images. When using reportlab, I experienced that the images were automatically compressed, and the image quality reduced.

The disadvantage of pylatex is that, since it is based on LaTex, it can be hard to place images exactly where you want on the page. However, I have found that using the position argument in the Figure class, and sometimes Subfigure, gives good enough results.

Example code for creating a pdf with a single image:

from pylatex import Document, Figure

doc = Document(documentclass="article")
with doc.create(Figure(position='p')) as fig:
fig.add_image('Lenna.png')

doc.generate_pdf('test', compiler='latexmk', compiler_args=["-pdf", "-pdflatex=pdflatex"], clean_tex=True)

In addition to installing pylatex (pip install pylatex), you need to install LaTex. For Ubuntu and other Debian systems you can run sudo apt-get install texlive-full. If you are using Windows I would recommend MixTex


fpdf works well for me. Much simpler than ReportLab and really free. Works with UTF-8.

참고URL : https://stackoverflow.com/questions/2252726/how-to-create-pdf-files-in-python

반응형