跳至主要内容

PDF处理

虚拟pdf打印机


pdfFactory 
开源



pdf阅读器

Sumatra PDF

https://www.sumatrapdfreader.org/



为什么 Python 用于 PDF 处理 

如您所知,PDF 处理属于文本分析。大多数文本分析库或框架仅使用 Python 设计。这为文本分析提供了优势。还有一件事,您永远无法在现有的机器学习或自然语言处理框架中直接处理 pdf。除非他们为此证明了显式接口。我们必须先将pdf转换为文本。我们可以使用下述任何库轻松实现这一点。

在线转换pdf

Sejda

每个文档 200 页的免费限制


PDF24 Tools

免费且易于使用的在线PDF工具

FreeOCR
http://www.paperfile.net/
适用于Windows的免费光学字符识别软件,支持大多数Twain扫描仪的扫描,还可以打开大多数扫描的PDF和多页Tiff图像以及流行的图像文件格式,FreeOCR输出纯文本,可以直接导出为Microsoft Word格式。不支持中文




wkhtmltopdf 和 wkhtmltoimage
是使用 QT Webkit 渲染引擎将 HTML 渲染为 PDF 和各种图像格式的命令行工具。这些完全“无头”运行,不需要显示或显示服务。
https://wkhtmltopdf.org/

django-wkhtmltopdf
允许 Django 站点输出动态 PDF。它利用wkhtmltopdf库,允许您使用您知道的技术(HTML 和 CSS)进行编写,并输出 PDF 文件

https://django-wkhtmltopdf.readthedocs.io/en/latest/

django-easy-pdf
https://pypi.org/project/django-easy-pdf/0.1.0/
这个应用程序使得在 Django 中渲染 PDF 文件非常容易。它可用于从简单的 HTML 标记和 CSS 样式创建发票、账单和其他文档。您甚至可以嵌入图像并使用自定义字体

WeasyPrint

是一种智能解决方案,可帮助 Web 开发人员创建 PDF 文档。它将简单的 HTML 页面变成华丽的统计报告、发票、票据……

从技术角度来看,WeasyPrint 是一个 HTML 和 CSS 的可视化渲染引擎,可以导出为 PDF。它旨在支持用于打印的 Web 标准。WeasyPrint 是在 BSD 许可下提供的免费软件

ReportLab

是久经考验、超强大的开源引擎,用于创建复杂的、数据驱动的 PDF 文档和自定义矢量图形。它是免费的、开源的,并且是用 Python 编写的。该软件包每月的下载量超过 50,000 次,是标准 Linux 发行版的一部分,嵌入在许多产品中,并被选中为维基百科的打印/导出功能提供支持。


PDFMiner

是一个从 PDF 文档中提取信息的工具。与其他 PDF 相关工具不同,它完全专注于获取和分析文本数据。PDFMiner 允许获取页面中文本的确切位置,以及其他信息,例如字体或线条。它包括一个 PDF 转换器,可以将 PDF 文件转换为其他文本格式(如 HTML)。它有一个可扩展的 PDF 解析器,可用于文本分析以外的其他目的


pikepdf

是一个新兴的用于 PDF 处理的 Python 库。它是 Python + QPDF = “py” + “qpdf” = “pyqpdf”。如果您查看 PyPDF2 和 pdfrw 之间的比较,您会看到,它提供了一些两者都没有的功能

pdfrw

是一个 Python 库和实用程序,用于读取和写入 PDF 文件

slate


PyPDF2

PyPDF2 是一个纯 python PDF 库,能够拆分、合并、裁剪和转换 PDF 文件的页面。它还可以向 PDF 文件添加自定义数据、查看选项和密码。它可以从 PDF 中检索文本和元数据,也可以将整个文件合并在一起。
https://pythonhosted.org/PyPDF2/index.html



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# 锁定或加密PDF文件
from PyPDF2 import PdfFileReader, PdfFileWriter

encrypted_file = PdfFileWriter()
original = PdfFileReader("simple_demo.pdf")
number_of_pages = original.numPages

for i in range(number_of_pages):
    page = original.getPage(i)
    encrypted_file.addPage(page)

password = "medium"
encrypted_file.encrypt(password)

with open("new_encrypted.pdf","wb")as file:
    encrypted_file.write(file)                                                                    



# 解锁或解密 PDF 文件
import pikepdf
from tqdm import tqdm

passwords = [line.strip() for line in open("passwordlist.txt")]
for password in tqdm(passwords, "Decrypting PDF"):
    try:
        with pikepdf.open("new_encrypted.pdf", password=password) as pdf:
            print(f"Password for the PDF file is {password}")
            break
    except pikepdf._qpdf.PasswordError as e:
        continue



# 用Python创建PDF文件
from reportlab.pdfgen import canvas
report = canvas.Canvas("file1.pdf")
report.drawString(50, 800, "This is an example for Medium")
report.save()



# 合并多个PDF文件
from PyPDF2 import PdfFileReader, PdfFileMerger

first_file = PdfFileReader("file1.pdf")
second_file = PdfFileReader("file2.pdf")

output = PdfFileMerger()

output.append(first_file)
output.append(second_file)
output.write("new_merged.pdf")



# 给PDF文件添加水印
from PyPDF2 import PdfFileReader,PdfFileWriter

original_file = "file1.pdf"
watermarked_pdf = "PDF_watermarked.pdf"
output_file = "output.pdf"

input_file = open(original_file, 'rb')
input_pdf = PdfFileReader(input_file)
watermark_file = open(watermarked_pdf, 'rb')
watermark_pdf = PdfFileReader(watermark_file)
watermark_page = watermark_pdf.getPage(0)
pdf_page = input_pdf.getPage(0)

pdf_page.mergePage(watermark_page)
output = PdfFileWriter()
output.addPage(pdf_page)
output_file = open(output_file, 'wb')
output.write(output_file)
output_file.close()
watermark_file.close()
input_file.close()


识别pdf


pdfplumber


Camelot

仅适用于基于文本的PDF,不适用于扫描的文档

pip install "camelot-py[cv]"



tika

https://tika.apache.org/

https://github.com/chrismattmann/tika-python

https://stackoverflow.com/questions/17098675/searching-text-in-a-pdf-using-python

https://stackoverflow.com/questions/33073972/how-can-i-use-tika-packagehttps-github-com-chrismattmann-tika-python-in-pyth


https://tika.apache.org/1.25/gettingstarted.html

# 批量处理

E:\>java -jar E:\tika-app-1.25.jar -i D:\DZFP\PDF -o D:\DZFP\Parse -t

首先下载并运行服务

java -jar C:\tika-server-1.25.jar

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import tika
tika.TikaClientOnly = True
from tika import parser

parsed = parser.from_file(r"E:\新建文件夹\031001700211_53042251.pdf",xmlContent=True)
# print(parsed["metadata"])
print(parsed["content"])

my_dict=parsed["metadata"]

import json
# print(json.dumps(my_dict, ensure_ascii=False, indent=4, sort_keys=True))
# print(dir(my_dict.get("resourceName")))
name = my_dict.get("resourceName")
fp_hm =name.split("'")[1].split('.')[0].split("_")[0]
fp_dm =name.split("'")[1].split('.')[0].split("_")[1]
print(fp_hm,fp_dm)
if fp_dm in parsed["content"] and fp_hm in parsed["content"]:
    print("匹配成功")
else:
    print("匹配不成功")


# 修改服务端口
# java -jar C:\tika-server-1.25.jar --port 1001


import tika
from tika import parser
parsed = parser.from_file(r"C:\Users\DANG\Downloads\031001700211_53042251.pdf",'http://localhost:1001/')
# print(parsed["metadata"])
# print(parsed["content"])
print(type(parsed["content"]))
print(parsed["content"].split()[65:])
print(len(parsed["content"].split()))

# import parser object from tike 
from tika import parser 

# opening pdf file 
parsed_pdf = parser.from_file(r"C:\Users\DANG\Downloads\031001700211_53042251.pdf") 

# saving content of pdf 
# you can also bring text only, by parsed_pdf['text'] 
# parsed_pdf['content'] returns string 
data = parsed_pdf['content'] 

# Printing of content 
print(data) 

# <class 'str'> 
print(type(data))
  
# ['metadata'] attribute returns  
# key-value pairs of meta-data  
print(parsed_pdf['metadata'])  
  
# <class 'dict'> 
print(type(parsed_pdf['metadata']))
# Returns keys applicable for given pdf. 
print(parsed_pdf.keys())





评论

此博客中的热门博文

Chrome浏览器

谷歌搜索 双引号——精确搜索 冒号后加文件类型——搜索特定类型的结果 关键词 后 site:**——搜索特定网站的关键词 +、-关键词——实现特定需求筛选 Google中/——快捷键入浏览·搜索框 关键词后..——搜索特定范围(地点)关键词 intitle:关键词——搜索特定标题 用 puppeteer 直接运行 chrome 爬 https://github.com/puppeteer/puppeteer Puppeteer 是一个 Node 库,它提供了一个高级 API 来通过 DevTools 协议 控制 Chrome 或 Chromium 。Puppeteer默认 无头 运行,但可以配置为运行完整(非无头)Chrome 或 Chromium。 了解如何为 Chrome 开发扩展程序 https://developer.chrome.com/docs/extensions/mv3/ 什么是Chrome插件 https://github.com/sxei/chrome-plugin-demo Google Workspace 状态信息中心 https://www.google.com/appsstatus#hl=zh&v=status 此页面提供属于“Google Workspace”的服务的状态信息 谷歌浏览器离线下载 https://support.google.com/chrome/answer/95346?co=GENIE.Platform%3DDesktop&hl=zh-Hans 企业版 https://cloud.google.com/chrome-enterprise/browser/download 也可以在谷歌浏览器 帮助中心 中搜索chrome https://www.google.com/intl/zh-CN/chrome/?standalone=1 chrome 打开新网页时不要覆盖 鼠标 中键(滚轮)点击超链接 ,或者右击超链接,选择新标签页打开, 还有点链接的同时按下 Ctrl 键也可以 谷歌在线翻译网页 http://translate.google.com/translate?u= http://www.dropitproject.com/index.php 打开chrome浏览器按 F6 ,等同于按 ...

python 之 configparser、configobj(ini配置文件)

ini 即 Initialize 初始化之意,通常由节(Section)、键(key)和值(value)组成 ini修改工具 https://visionlore.com/lab/ini_editor.php https://www.horstmuc.de/wbat32.htm#inifile 语法      INIFILE filename.ini [section] item=string # db.ini 中的内容 # ********************* # [localdb] # host     = 127.0.0.1 # user     = root # password = 123456 # port     = 3306 # database = mysql # *********************   import pymysql from configparser import ConfigParser   cfg = ConfigParser ( ) cfg. read ( "db.ini" )   print ( cfg. items ( "localdb" ) ) db_cfg = dict ( cfg. items ( "localdb" ) ) print ( db_cfg )   # 端口port类型str转为int db_cfg [ 'port' ] = int ( db_cfg [ 'port' ] ) con = pymysql. connect ( **db_cfg )   from pprint import pprint lst = [ line. strip ( ) for line in open ( 'db.ini' ) ] pprint ( lst ) http://www.voidspace.org.uk/python/articles/configobj.shtml https://configobj.readthedocs.io/en/latest/configobj.html https://pythonhosted.or...

python 代码示例

  加密软件 谷歌搜registration codes python和license keys python https://www.nuvovis.com/python-software-licensing.html https://build-system.fman.io/generating-license-keys https://codereview.stackexchange.com/questions/95499/register-login-and-authentication-through-terminal 获取MAC地址并生成序列号,从序列号生成激活密钥 secrets模块资料 https://blog.miguelgrinberg.com/post/the-new-way-to-generate-secure-tokens-in-python # 不足十位左边加零 while True:     num = input('Enter a number : ')     print('The zero-padded number is : ', str(num).rjust(10, '0')) 查找n个自然数的和 # Sum of natural numbers up to num   num = 16   if num < 0 :     print ( "Enter a positive number" ) else :     sum = 0     # use while loop to iterate until zero     while ( num > 0 ) :         sum + = num        num - = 1     print ( "The sum is" , sum )   使用匿名函数显示整数2的幂 # Display the powers of 2 using anonymous function ...