This article mainly introduces you to the method of using python program to generate word and PDF documents. The article gives a detailed introduction and sample code. I believe it has certain reference value for everyone. Friends in need can join us below. Let's see.
1. How to export word documents through the program
Export web/html content into world documents. There are many solutions in Java. For example, using various methods such as Jacob, Apache POI, Java2Word, iText, etc., as well as using template engines such as freemarker. There are also some corresponding methods in PHP, but there are very few ways to generate world documents from web/html content in Python. The most difficult thing to solve is how to use js code to asynchronously obtain the filled data and export the pictures into a word document.
1. unoconv
Function:
#1. Supports converting local html documents to Documents in docx format, so you need to save the html files in the web page locally and then call unoconv for conversion. The conversion effect is also good and the method of use is very simple.
\# 安装 sudo apt-get install unoconv \# 使用 unoconv -f pdf *.odt unoconv -f doc *.odt unoconv -f html *.odt
Disadvantages:
1. Only static html can be converted. For pages with Where ajax is used to obtain data asynchronously, it cannot be converted (mainly to ensure that there is data in the html file saved from the web page).
2. Only html can be converted. If there are pictures generated using echarts, highcharts and other js codes in the page, these pictures cannot be converted into word documents;
3. The content format of the generated word document is not easy to control.
2. python-docx
Function:
1.python- docx is a python library that can read and write word documents.
Usage:
1. Obtain the data from the web page and add it to the word document using python manual typesetting.
from docx import Document from docx.shared import Inches document = Document() document.add_heading('Document Title', 0) p = document.add_paragraph('A plain paragraph having some ') p.add_run('bold').bold = True p.add_run(' and some ') p.add_run('italic.').italic = True document.add_heading('Heading, level 1', level=1) document.add_paragraph('Intense quote', style='IntenseQuote') document.add_paragraph( 'first item in unordered list', style='ListBullet' ) document.add_paragraph( 'first item in ordered list', style='ListNumber' ) document.add_picture('monty-truth.png', width=Inches(1.25)) table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' for item in recordset: row_cells = table.add_row().cells row_cells[0].text = str(item.qty) row_cells[1].text = str(item.id) row_cells[2].text = item.desc document.add_page_break() document.save('demo.docx')
from docx import Document from docx.shared import Inches document = Document() for row in range(9): t = document.add_table(rows=1,cols=1,style = 'Table Grid') t.autofit = False #很重要! w = float(row) / 2.0 t.columns[0].width = Inches(w) document.save('table-step.docx')
Disadvantages:
Features Very weak. There are many limitations, such as not supporting templates, etc., and can only generate simple format word documents.
2. Method of exporting PDF documents from the program
1.pdfkit
Function:
1.wkhtmltopdf is mainly used to generate PDF from HTML.
2.pdfkit is a python package based on wkhtmltopdf, which supports the conversion of URLs, local files, and text content to PDF. It ultimately calls the wkhtmltopdf command. It is the best python that I have come across so far to generate pdf.
Advantages:
1.wkhtmltopdf: Convert HTML to PDF using webkit kernel
Webkit is an efficient, open source The browser kernel, which is used by browsers including Chrome and Safari. Chrome's function of printing the current web page has an option to directly "save as PDF".
2.wkhtmltopdf uses the PDF rendering engine of the webkit core to convert HTML pages to PDF. High fidelity, great conversion quality, and very easy to use.
Usage:
\# 安装 pip install pdfkit \# 使用 import pdfkit pdfkit.from_url('http://google.com', 'out.pdf') pdfkit.from_file('test.html', 'out.pdf') pdfkit.from_string('Hello!', 'out.pdf')
Disadvantages:
1. For js codes such as echarts and highcharts The generated icon cannot be converted to pdf (because its function is mainly to convert html to pdf, not js to pdf). The conversion effect for purely static pages is still good.
2. Others
Other plug-ins for generating pdf include: weasyprint, reportlab, PyPDF2, etc. After simple tests, they are not as effective as pdfkit, and some are complicated to use.
For more related articles on how to use python programs to generate word and PDF documents, please pay attention to the PHP Chinese website!

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
