PDF에서 페이지를 JPEG로 추출
파이썬 코드에서 PDF의 특정 페이지를 JPEG 파일로 효율적으로 저장하려면 어떻게 해야 합니까?
사용 사례:저는 PDF가 업로드되고 각 페이지에 해당하는 JPEG가 저장되는 Python Flask 웹 서버를 가지고 있습니다.
이 솔루션은 가깝지만 전체 페이지를 JPEG로 변환하지 않는 것이 문제입니다.
pdf2 이미지 라이브러리를 사용할 수 있습니다.
다음을 사용하여 간단히 설치할 수 있습니다.
pip install pdf2image
설치가 완료되면 다음 코드를 사용하여 이미지를 가져올 수 있습니다.
from pdf2image import convert_from_path
pages = convert_from_path('pdf_file', 500)
페이지를 JPEG 형식으로 저장
for count, page in enumerate(pages):
page.save(f'out{count}.jpg', 'JPEG')
편집: Github repo pdf2 이미지는 또한 사용한다고 언급합니다.pdftoppm
다른 설치가 필요합니다.
pdftopm은 실제 마법을 수행하는 소프트웨어입니다.그것은 포플러라고 불리는 더 큰 패키지의 일부로 배포됩니다.Windows 사용자는 Windows용 포플러를 설치해야 합니다.Mac 사용자는 Mac용 포플러를 설치해야 합니다. Linux 사용자는 디스트리뷰터(Ubuntu 및 Archlinux에서 테스트됨)와 함께 pdftopm을 사전 설치해야 합니다. 그렇지 않으면 실행합니다.
sudo apt install poppler-utils
.
다음을 수행하여 아나콘다를 사용하여 Windows에서 최신 버전을 설치할 수 있습니다.
conda install -c conda-forge poppler
참고: 0.67까지의 Windows 버전은 http://blog.alivate.com.au/poppler-windows/ 에서 이용할 수 있지만 0.68은 2018년 8월에 출시되었으므로 최신 기능이나 버그 수정을 받을 수 없습니다.
저는 이 간단한 해결책인 PyMuPDF 출력 toppng 파일을 찾았습니다.라이브러리를 사용하는 렌더링 엔진의 과거 이름인 "fitz"로 가져옵니다.
import fitz
pdffile = "infile.pdf"
doc = fitz.open(pdffile)
page = doc.load_page(0) # number of page
pix = page.get_pixmap()
output = "outfile.png"
pix.save(output)
doc.close()
참고: 라이브러리가 "camelCase"에서 "snake_case"로 변경되었습니다.함수가 존재하지 않는 오류가 발생하면 사용되지 않는 이름으로 확인합니다.위 예제의 기능이 그에 따라 업데이트되었습니다.
그fitz.Document
클래스는 컨텍스트 관리자 초기화를 지원합니다.
with fitz.open(pdffile) as doc:
...
사용(v4):
python3 -m pip install "pypdfium2==4"
import pypdfium2 as pdfium
# Load a document
filepath = "tests/resources/multipage.pdf"
pdf = pdfium.PdfDocument(filepath)
# render a single page (in this case: the first one)
page = pdf[0]
pil_image = page.render(scale=2).to_pil()
pil_image.save("output.jpg")
# render multiple pages concurrently (in this case: all)
page_indices = [i for i in range(len(pdf))]
renderer = pdf.render(pdfium.PdfBitmap.to_pil, page_indices=page_indices)
for index, image in zip(page_indices, renderer):
image.save("output_%02d.jpg" % index)
장점:
- PDFium은 자유형 라이센스(BSD 3-Clause 또는 Apache 2.0, 선택 가능)
- 그것은 빠르며, 포플러를 능가합니다.속도 면에서, pypdfium2는 거의 도달할 수 있습니다.
- 필요에 따라 , , 바이트 또는 actypes 배열을 반환합니다.
- 암호화된(암호로 보호된) PDF를 처리할 수 있습니다.
- 필수 런타임 종속성 없음
- Python >= 3.6 지원
- 설치 인프라가 PEP 517/518을 준수합니다.
휠은 현재 다음 용도로 사용할 수 있습니다.
Windows
amd64, win32, arm64macOS
암64x86_64,44064Linux (glibc 2.26+)
, i686, arch64, armv7lLinux (musl 1.2+)
i686x86_64, i686
소스에서 빌드할 스크립트도 있습니다.
(거부자:내가 저자야)
라이브러리pdf2image
(다른 답변에 사용됨) 사실 시작 이상의 기능을 제공하지 않습니다. pdttoppm
와 함께subprocess.Popen
다음은 이를 직접 수행하는 짧은 버전입니다.
PDFTOPPMPATH = r"D:\Documents\software\____PORTABLE\poppler-0.51\bin\pdftoppm.exe"
PDFFILE = "SKM_28718052212190.pdf"
import subprocess
subprocess.Popen('"%s" -png "%s" out' % (PDFTOPPMPATH, PDFFILE))
은 다은음 Windows 설니다입의 링크입니다.pdftoppm
(포플러라는 이름의 패키지에 포함됨): http://blog.alivate.com.au/poppler-windows/ .
운영 체제에 Popler를 설치할 필요가 없습니다.이렇게 하면 됩니다.
pip install Wand
from wand.image import Image
f = "somefile.pdf"
with(Image(filename=f, resolution=120)) as source:
for i, image in enumerate(source.sequence):
newfilename = f.removesuffix(".pdf") + str(i + 1) + '.jpeg'
Image(image).save(filename=newfilename)
@gaurwraith, 윈도우즈용 popler를 설치하고 pdftopm을 사용합니다.exe는 다음과 같습니다.
http://blog.alivate.com.au/poppler-windows/ 에서 Popler의 최신 바이너리/dll이 포함된 zip 파일을 다운로드하여 프로그램 파일 폴더의 새 폴더로 압축을 풉니다.예: "C:\Program Files (x86)\Poppler"를 클릭합니다.
SYSTEM PATH 환경 변수에 "C:\Program Files (x86)\Poppler\Poppler-0.68.0\bin"을 추가합니다.
cmd line install pdf2 image module -> "pip install pdf2 image" 에서 설치합니다.
- 또는 pdftoppm을 직접 실행합니다.사용자 Basj가 설명한 대로 Python의 하위 프로세스 모듈을 사용하여 코드에서 exe.
@vishvAsvAsuki, 이 코드는 주어진 폴더에 있는 하나 이상의 pdfs의 모든 페이지에 대해 하위 프로세스 모듈을 통해 원하는 jpgs를 생성해야 합니다.
import os, subprocess
pdf_dir = r"C:\yourPDFfolder"
os.chdir(pdf_dir)
pdftoppm_path = r"C:\Program Files (x86)\Poppler\poppler-0.68.0\bin\pdftoppm.exe"
for pdf_file in os.listdir(pdf_dir):
if pdf_file.endswith(".pdf"):
subprocess.Popen('"%s" -jpeg %s out' % (pdftoppm_path, pdf_file))
또는 pdf2 이미지 모듈 사용:
import os
from pdf2image import convert_from_path
pdf_dir = r"C:\yourPDFfolder"
os.chdir(pdf_dir)
for pdf_file in os.listdir(pdf_dir):
if pdf_file.endswith(".pdf"):
pages = convert_from_path(pdf_file, 300)
pdf_file = pdf_file[:-4]
for page in pages:
page.save("%s-page%d.jpg" % (pdf_file,pages.index(page)), "JPEG")
GhostScript는 Linux 기반 시스템의 경우 Popler보다 훨씬 빠른 성능을 제공합니다.
다음은 pdf에서 이미지로 변환하는 코드입니다.
def get_image_page(pdf_file, out_file, page_num):
page = str(page_num + 1)
command = ["gs", "-q", "-dNOPAUSE", "-dBATCH", "-sDEVICE=png16m", "-r" + str(RESOLUTION), "-dPDFFitPage",
"-sOutputFile=" + out_file, "-dFirstPage=" + page, "-dLastPage=" + page,
pdf_file]
f_null = open(os.devnull, 'w')
subprocess.call(command, stdout=f_null, stderr=subprocess.STDOUT)
할 수 , macOS의 고스트스크립트를 사용할 수 있습니다.brew install ghostscript
다른 플랫폼에 대한 설치 정보는 여기에서 확인할 수 있습니다.시스템에 아직 설치되지 않은 경우.
그들은 pdftojpg라는 유틸리티로 pdf를 img로 변환하는 데 사용할 수 있습니다.
코드는 https://github.com/pankajr141/pdf2jpg 에서 확인할 수 있습니다.
from pdf2jpg import pdf2jpg
inputpath = r"D:\inputdir\pdf1.pdf"
outputpath = r"D:\outputdir"
# To convert single page
result = pdf2jpg.convert_pdf2jpg(inputpath, outputpath, pages="1")
print(result)
# To convert multiple pages
result = pdf2jpg.convert_pdf2jpg(inputpath, outputpath, pages="1,0,3")
print(result)
# to convert all pages
result = pdf2jpg.convert_pdf2jpg(inputpath, outputpath, pages="ALL")
print(result)
모든 사람이 직면하게 될 한 가지 문제는 포플러 설치입니다.나의 방식은 까다롭지만 효율적으로 작동할 것입니다.
여기서 포플러를 첫 번째 다운로드합니다.
그런 다음 추출하고 코드 섹션에 추가합니다.poppler_path=r'C:\Program Files\poppler-0.68.0\bin'
를 들어) 아래와 (으)ㄹ 수 있습니다.
from pdf2image import convert_from_path
images = convert_from_path("mypdf.pdf", 500,poppler_path=r'C:\Program Files\poppler-0.68.0\bin')
for i, image in enumerate(images):
fname = 'image'+str(i)+'.png'
image.save(fname, "PNG")
하나 이상의 페이지가 있는 PDF 파일을 하나의 병합된 JPEG 이미지로 변환하는 기능이 있습니다.
import os
import tempfile
from pdf2image import convert_from_path
from PIL import Image
def convert_pdf_to_image(file_path, output_path):
# save temp image files in temp dir, delete them after we are finished
with tempfile.TemporaryDirectory() as temp_dir:
# convert pdf to multiple image
images = convert_from_path(file_path, output_folder=temp_dir)
# save images to temporary directory
temp_images = []
for i in range(len(images)):
image_path = f'{temp_dir}/{i}.jpg'
images[i].save(image_path, 'JPEG')
temp_images.append(image_path)
# read images into pillow.Image
imgs = list(map(Image.open, temp_images))
# find minimum width of images
min_img_width = min(i.width for i in imgs)
# find total height of all images
total_height = 0
for i, img in enumerate(imgs):
total_height += imgs[i].height
# create new image object with width and total height
merged_image = Image.new(imgs[0].mode, (min_img_width, total_height))
# paste images together one by one
y = 0
for img in imgs:
merged_image.paste(img, (0, y))
y += img.height
# save merged image
merged_image.save(output_path)
return output_path
사용 예: -
convert_pdf_to_image("path_to_Pdf/1.pdf", "output_path/output.jpeg")
PDF(단일 페이지)가 포함된 폴더 디렉토리를 PNG로 정말 멋지게 변환하기 위해 이 스크립트를 작성했습니다.
import os
from pathlib import PurePath
import glob
# from PIL import Image
from pdf2image import convert_from_path
import pdb
# In[file list]
wd = os.getcwd()
# filter images
fileListpdf = glob.glob(f'{wd}//*.pdf')
# In[Convert pdf to images]
for i in fileListpdf:
images = convert_from_path(i, dpi=300)
path_split = PurePath(i).parts
fileName, ext = os.path.splitext(path_split[-1])
images[0].save(f'{fileName}.png', 'PNG')
PDF를 PNG로 변환해야 하는 경우에 도움이 되기를 바랍니다!
저는 (아마도) 훨씬 더 간단한 pdf2 이미지 옵션을 사용합니다.
cd $dir
for f in *.pdf
do
if [ -f "${f}" ]; then
n=$(echo "$f" | cut -f1 -d'.')
pdftoppm -scale-to 1440 -png $f $conv/$n
rm $f
mv $conv/*.png $dir
fi
done
이것은 좁은 주조 장치를 사용하기 위한 루프에 있는 배시 스크립트의 작은 부분입니다.추가된 PDF 파일(모두)을 5초마다 확인하고 처리합니다.이것은 데모 장치용이며, 마지막에 변환은 원격 서버에서 수행됩니다.지금은 .PNG로 변환 중이지만 .JPG도 가능합니다.
이 변환은 A4 형식의 전환과 함께 비디오, 두 개의 부드러운 스크롤 텍스트 및 로고(세 가지 버전의 전환 포함)를 표시하여 Pi3를 거의 4x100% CPU 부하로 설정합니다 ;-)
from pdf2image import convert_from_path
import glob
pdf_dir = glob.glob(r'G:\personal\pdf\*') #your pdf folder path
img_dir = "G:\\personal\\img\\" #your dest img path
for pdf_ in pdf_dir:
pages = convert_from_path(pdf_, 500)
for page in pages:
page.save(img_dir+pdf_.split("\\")[-1][:-3]+"jpg", 'JPEG')
여기 추가 라이브러리가 필요 없고 매우 빠른 솔루션이 있습니다.이것은 다음에서 찾을 수 있습니다: https://nedbatchelder.com/blog/200712/extracting_jpgs_from_pdfs.html # 좀 더 편리하게 하기 위해 코드를 함수에 추가했습니다.
def convert(filepath):
with open(filepath, "rb") as file:
pdf = file.read()
startmark = b"\xff\xd8"
startfix = 0
endmark = b"\xff\xd9"
endfix = 2
i = 0
njpg = 0
while True:
istream = pdf.find(b"stream", i)
if istream < 0:
break
istart = pdf.find(startmark, istream, istream + 20)
if istart < 0:
i = istream + 20
continue
iend = pdf.find(b"endstream", istart)
if iend < 0:
raise Exception("Didn't find end of stream!")
iend = pdf.find(endmark, iend - 20)
if iend < 0:
raise Exception("Didn't find end of JPG!")
istart += startfix
iend += endfix
jpg = pdf[istart:iend]
newfile = "{}jpg".format(filepath[:-3])
with open(newfile, "wb") as jpgfile:
jpgfile.write(jpg)
njpg += 1
i = iend
return newfile
인수로 pdf 경로를 사용하여 convert를 호출하면 함수가 동일한 디렉토리에 .jpg 파일을 생성합니다.
여러 페이지가 있는 PDF 파일의 경우 다음이 가장 좋고 단순합니다(pdf2 image-1.14.0 사용).
from pdf2image import convert_from_path
from pdf2image.exceptions import (
PDFInfoNotInstalledError,
PDFPageCountError,
PDFSyntaxError
)
images = convert_from_path(r"path/to/input/pdf/file", output_folder=r"path/to/output/folder", fmt="jpg",) #dpi=200, grayscale=True, size=(300,400), first_page=0, last_page=3)
images.clear()
참고:
- "images"는 PIL 이미지 목록입니다.
- 출력 폴더에 저장된 이미지에는 시스템에서 생성된 이름이 있으며, 필요한 경우 나중에 이름을 변경할 수 있습니다.
이 쉬운 스크립트는 PDF(단일/다중 페이지)가 포함된 폴더 디렉토리를 JPEG로 변환할 수 있습니다.
from PIL import Image
import pytesseract
import sys
from pdf2image import convert_from_path
import os
from os import listdir
from os import system
from os.path import isfile, join, basename, dirname
import shutil
def move_processed_file(file, doc_path, download_processed):
try:
shutil.move(doc_path + '/' + file, download_processed + '/' + file)
pass
except Exception as e:
print(e.errno)
raise
else:
pass
finally:
pass
pass
def run_conversion():
root_dir = os.path.abspath(os.curdir)
doc_path = root_dir + r"\data\download"
pdf_processed = root_dir + r"\data\download\pdf_processed"
results_folder = doc_path
files = [f for f in listdir(doc_path) if isfile(join(doc_path, f))]
pdf_files = [f for f in listdir(doc_path) if isfile(join(doc_path, f)) and f.lower().endswith('.pdf')]
# check OS type
if os.name == 'nt':
# if is windows or a graphical OS, change this poppler path with your own path
poppler_path = r"C:\poppler-0.68.0\bin"
else:
poppler_path = root_dir + r"\usr\bin"
for file in pdf_files:
'''
# Converting PDF to images
'''
# Store all the pages of the PDF in a variable
pages = convert_from_path(doc_path + '/' + file, 500, poppler_path=poppler_path)
# Counter to store images of each page of PDF to image
image_counter = 1
filename, file_extension = os.path.splitext(file)
# Iterate through all the pages stored above
for page in pages:
# Declaring filename for each page of PDF as JPG
# PDF page n -> page_n.jpg
filename = filename + '_' + str(image_counter) + ".jpg"
# Save the image of the page in system
page.save(results_folder + '/' + filename, 'JPEG')
# Increment the counter to update filename
image_counter += 1
move_processed_file(file, doc_path, pdf_processed)
from pdf2image import convert_from_path
PDF_file = 'Statement.pdf'
pages = convert_from_path(PDF_file, 500,userpw='XXX')
image_counter = 1
for page in pages:
filename = "foldername/page_" + str(image_counter) + ".jpg"
page.save(filename, 'JPEG')
image_counter = image_counter + 1
언급URL : https://stackoverflow.com/questions/46184239/extract-a-page-from-a-pdf-as-a-jpeg
'programing' 카테고리의 다른 글
하나의 data.frame에서 두 번째 data.frame에 없는 행을 선택합니다. (0) | 2023.06.06 |
---|---|
Git를 누르기 전에 여러 커밋 결합 (0) | 2023.06.06 |
브라우저를 통해 mongodb에 액세스할 수 없음 - 네이티브 드라이버 포트에서 HTTP를 통해 MongoDB에 액세스하려고 하는 것 같습니다. (0) | 2023.06.06 |
dplyr로 여러 열을 요약하시겠습니까? (0) | 2023.06.06 |
오류: Firebase ID 토큰이 만료되었습니다. (0) | 2023.06.06 |