Hướng dẫn how to create pdf files in python using pdfkit - cách tạo file pdf trong python bằng pdfkit

Hướng dẫn how to create pdf files in python using pdfkit - cách tạo file pdf trong python bằng pdfkit

Trong một bài viết trước, chúng tôi đã nói về một số cách để đọc các tệp PDF với Python. Bài đăng này sẽ bao gồm hai gói được sử dụng để tạo các tệp PDF với Python, bao gồm PDFKit và Báo cáo.pdfkit and ReportLab.

Tạo các tệp pdf với python và pdfkit

PDFKIT là thư viện đầu tiên tôi học được để tạo các tệp PDF. Một tính năng hay của PDFKit là bạn có thể sử dụng nó để tạo các tệp PDF từ URL. Để bắt đầu, bạn sẽ cần cài đặt nó cùng với một tiện ích gọi là wkhtmltopdf. Sử dụng PIP để cài đặt PDFKIT từ PYPI: was the first library I learned for creating PDF files. A nice feature of pdfkit is that you can use it to create PDF files from URLs. To get started, you’ll need to install it along with a utility called wkhtmltopdf. Use pip to install pdfkit from PyPI:

pip install pdfkit

Khi bạn đã thiết lập, bạn có thể bắt đầu sử dụng pdfkit. Trong ví dụ dưới đây, chúng tôi tải xuống trang chính của Wikipedia, dưới dạng tệp PDF. Để làm cho pdfkit hoạt động, bạn sẽ cần thêm wkhtmltopdf vào đường dẫn của bạn hoặc định cấu hình pdfkit để chỉ ra nơi lưu trữ thực thi (tùy chọn sau được sử dụng bên dưới).pdfkit. In the example below, we download Wikipedia’s main page as a PDF file. To get pdfkit working, you’ll need to either add wkhtmltopdf to your PATH, or configure pdfkit to point to where the executable is stored (the latter option is used below).

Tải xuống một trang web dưới dạng PDF

# import package
import pdfkit

# configure pdfkit to point to our installation of wkhtmltopdf
config = pdfkit.configuration(wkhtmltopdf = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")

# download Wikipedia main page as a PDF file
pdfkit.from_url("https://en.wikipedia.org/wiki/Main_Page", "sample_url_pdf.pdf", configuration = config)

Bạn cũng có thể đặt đường dẫn đầu ra thành FALSE, sẽ trả lại phiên bản nhị phân của PDF thành Python, thay vì tải trang web vào tệp bên ngoài.

pdfkit.from_url("https://en.wikipedia.org/wiki/Main_Page", output_path = False, configuration = config)

Cách tạo PDF từ HTML

Một trong những tính năng đẹp nhất của PDFKIT là bạn có thể sử dụng nó để tạo các tệp PDF từ HTML, bao gồm từ các chuỗi HTML mà bạn truyền trực tiếp trong Python.pdfkit is that you can use it to create PDF files from HTML, including from HTML strings that you pass it directly in Python.

s = """

Sample PDF file from HTML



First line...

Second line...

Third line...

""" pdfkit.from_string(s, output_path = "new_file.pdf", configuration = config)

Ngoài ra, PDFKit có thể tạo các tệp PDF bằng cách đọc các tệp HTML.pdfkit can create PDF files by reading HTML files.

pdfkit.from_file("sample_html_file.html", output_path = "new_file2.pdf", configuration = config)

Bạn cũng có thể tạo các tệp PDF với HTML / CSS phức tạp hơn. Bạn chỉ cần chuyển HTML dưới dạng chuỗi hoặc lưu trữ nó trong một tệp có thể được chuyển cho PDFKit. Hãy cùng làm một ví dụ khác, nhưng lần này, chúng tôi sẽ tạo một bảng bằng HTML và CSS.pdfkit. Let’s do another example, but this time, we’ll create a table using HTML and CSS.

Tạo bảng trong tệp PDF

table_html = """






Sample Table

Field 1 Field 2
x1 x2
x3 x4
""" pdfkit.from_string(table_html, output_path = "sample_table.pdf", configuration = config)

Hướng dẫn how to create pdf files in python using pdfkit - cách tạo file pdf trong python bằng pdfkit

Tạo các tệp PDF với Python và Báo cáo

Gói tiếp theo mà chúng tôi sẽ thảo luận là Báo cáo. Báo cáo là một trong những libaries phổ biến nhất để tạo các tệp PDF.ReportLab. ReportLab is one of the most popular libaries for creating PDF files.

Bạn có thể cài đặt Báo cáo bằng PIP:ReportLab using pip:

pip install reportlab

Dưới đây, một ví dụ ban đầu để tạo PDF đơn giản với một dòng văn bản. Phần đầu tiên của mã nhập mô -đun Canvas từ Báo cáo. Sau đó, chúng tôi tạo ra một thể hiện của lớp Canvas (lưu ý vốn Cap Caps lần này) với tên của tệp chúng tôi muốn tạo. Thứ ba, chúng tôi sử dụng dây rút để viết ra một dòng văn bản. (50, 800) là tọa độ để đặt văn bản (điều này có thể mất một số thử nghiệm). Cuối cùng, chúng tôi lưu tệp.ReportLab. Then, we create an instance of the Canvas (note the capital “C” this time) class with the name of the file we want to create. Third, we use drawString to write out a line of text. The (50, 800) are coordinates for where to place the text (this might take some experimentation). Lastly, we save the file.

from reportlab.pdfgen import canvas

report = canvas.Canvas("first_test.pdf")

report.drawString(50, 800, "**First PDF with ReportLab**")
report.save()

Thêm hình ảnh vào tệp PDF

Tiếp theo, hãy để tạo ra một tệp PDF mẫu chứa hình ảnh. Ở đây, chúng tôi sẽ sử dụng thư viện gối để tạo một đối tượng hình ảnh. Trong ví dụ này, chúng tôi cần tạo một danh sách các yếu tố mà chúng tôi sẽ sử dụng để xây dựng tệp PDF (chúng tôi gọi danh sách này là thông tin bên dưới). Đối với trường hợp này, danh sách sẽ chỉ chứa một phần tử - đối tượng hình ảnh đại diện cho hình ảnh mà chúng ta sẽ đưa vào tệp PDF, nhưng như chúng ta sẽ thấy trong ví dụ tiếp theo, chúng ta cũng có thể sử dụng danh sách này để lưu trữ các yếu tố khác để đặt vào tệp PDF.pillow library to create an Image object. In this example, we need to create a list of elements that we will use to construct the PDF file (we refer to this list as info below). For this instance, the list will contain just one element – the Image object represeting the image that we will put into the PDF file, but as we’ll see in the next example, we can also use this list to store other elements for placing into the PDF file.

Ngoài ra, lưu ý ở đây chúng tôi đang sử dụng lớp SimpleDoctemplate, về cơ bản thực hiện những gì nó nghe - tạo ra một mẫu tài liệu đơn giản mà chúng tôi có thể sử dụng để điền thông tin. Điều này cung cấp nhiều cấu trúc hơn là sử dụng vải, như trên.SimpleDocTemplate class, which basically does what it sounds like – creates a simple document template that we can use to fill in information. This provides more structure than using canvas, like above.

# import in SimpleDocTemplate
from reportlab.platypus import SimpleDocTemplate
from PIL import Image

# create document object
doc = SimpleDocTemplate("sample_image.pdf")
info = []

# directory to image file we want to use
image_file = "sample_plot.png"

# create Image object with size specifications
im = Image(image_file, 3*inch, 3*inch)

# append Image object to our info list
info.append(im)

# build / save PDF document
doc.build(info)

Tạo các đoạn văn của văn bản

Tổng quát hóa mã của chúng tôi ở trên, chúng tôi có thể thêm một vài đoạn văn bản, tiếp theo là một hình ảnh mẫu.

from reportlab.platypus import Paragraph

doc = SimpleDocTemplate("more_text.pdf")

p1 = "This is the first paragraph..."
p2 = "This is the second paragraph..."
p3 = "This is the third paragraph..."
p4 = "





" image_file = "sample_plot.png" im = Image(image_file, 3*inch, 3*inch) info = [] info.append(Paragraph(p1)) info.append(Paragraph(p2)) info.append(Paragraph(p3)) info.append(Paragraph(p4)) info.append(im) doc.build(info)

Cách điều chỉnh phông chữ

Để điều chỉnh các loại phông chữ, chúng tôi có thể điều chỉnh ví dụ báo cáo đầu tiên của chúng tôi ở trên để sử dụng phương thức SetFont.ReportLab example above to use the setFont method.

# import package
import pdfkit

# configure pdfkit to point to our installation of wkhtmltopdf
config = pdfkit.configuration(wkhtmltopdf = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")

# download Wikipedia main page as a PDF file
pdfkit.from_url("https://en.wikipedia.org/wiki/Main_Page", "sample_url_pdf.pdf", configuration = config)

0

Tạo PDF với nhiều trang

Tiếp theo, hãy để cho thấy cách tạo PDF với nhiều trang. Đây là một nhiệm vụ phổ biến và hữu ích để có thể làm. Để xử lý việc tạo nhiều trang, chúng tôi sẽ sửa đổi ví dụ trên để tạo PDF với ba trang riêng biệt. Một cách để nói với Báo cáo Nội dung trên một trang duy nhất được kết thúc là sử dụng phương thức ShowPage, như bên dưới. Bất kỳ nội dung nào bạn tạo sau đó sẽ được thêm vào trang tiếp theo. Sau đó, chúng ta có thể gọi lại phương thức ShowPage để tạo trang thứ ba.ReportLab the content on a single page is finished is to use the showPage method, like below. Any content you create afterward will be added to the next page. Then, we can call the showPage method again to create a third page.

# import package
import pdfkit

# configure pdfkit to point to our installation of wkhtmltopdf
config = pdfkit.configuration(wkhtmltopdf = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")

# download Wikipedia main page as a PDF file
pdfkit.from_url("https://en.wikipedia.org/wiki/Main_Page", "sample_url_pdf.pdf", configuration = config)

1

Một cách khác để tạo lỗi trang bằng cách sử dụng SimpleDoctemplate từ trước đó trong bài viết là như thế này:SimpleDocTemplate from earlier in the post is like this:

# import package
import pdfkit

# configure pdfkit to point to our installation of wkhtmltopdf
config = pdfkit.configuration(wkhtmltopdf = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")

# download Wikipedia main page as a PDF file
pdfkit.from_url("https://en.wikipedia.org/wiki/Main_Page", "sample_url_pdf.pdf", configuration = config)

2

Sự kết luận

Đó là nó cho bài viết này! Nếu bạn thích đọc sách, xin vui lòng chia sẻ bài viết này với bạn bè của bạn. Kiểm tra thêm về Báo cáo bằng cách nhấp vào đây. Tài liệu cho pdfkit là ở đây.ReportLab by clicking here. Documentation for pdfkit is here.