AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / computer / Perguntas / 1837459
Accepted
YorSubs
YorSubs
Asked: 2024-04-01 21:35:49 +0800 CST2024-04-01 21:35:49 +0800 CST 2024-04-01 21:35:49 +0800 CST

PowerShell, ImageMagick, GhostScript para extrair cada página de um PDF como uma imagem separada

  • 772

Gostaria de pegar um PDF e extrair cada página como uma imagem. Consegui fazer isso com ImageMagick e GhostScript, mas os resultados são de qualidade incrivelmente ruim. Eu tentei muitas opções de saída diferentes sem sorte. O script abaixo deve ser bastante autoexplicativo. Funciona, mas a qualidade da imagem é realmente péssima em comparação com a abertura do PDF.

  • Existe uma maneira de usar o ImageMagick de forma que a saída das imagens seja de boa qualidade?
  • Que tal usar outras ferramentas, mas de preferência de forma programática, já que processar muitos PDFs seria estranho se eu tivesse que fazê-los um por um em uma GUI.
# Extract each page from a PDF as a png using ImageMagick
# ImageMagick requires GhostScript for PDF manipulation so have to make sure that is installed
# Current install folder: C:\Program Files\ImageMagick-7.1.1-Q16-HDRI
# Chocolatey package does not inclued the 'identify.exe' command

# Path to the PDF file
$pdfFilePath = "C:\0\MyFile.pdf"
# Output directory for images
$outputDirectory = "C:\0"
# Image type to output to (tried jpg, png, tiff etc)
$imageExtension = "jpg"

# Check if running as Admin
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Host "Please run this script as an administrator."; exit }
# Check if Chocolatey is installed, if not, install it
if (!(Test-Path "$env:ProgramData\chocolatey")) { Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) }
# Check for magick.exe on path; if not installed, install ImageMagick
$imageMagickExePath = Get-ChildItem -Path "C:\Program Files\ImageMagick-*" -Filter "magick.exe" -Recurse | Select-Object -First 1 -ExpandProperty FullName
if (!(Get-Command "magick.exe" -ea silent) -and ($null -eq $imageMagickExePath)) { Write-Host "ImageMagick not found. Installing..."; choco install imagemagick -y }
if ($null -eq $imageMagickExePath) { Write-Host "Error: magick.exe not found at $imageMagickExePath"; exit }
Write-Host "magick.exe found at '$imageMagickExePath'"
# Check for gswin64.exe on path; if not installed, install GhostScript
$gsExePath = Get-ChildItem -Path "C:\Program Files\gs\gs*\bin" -Filter "gswin64.exe" -Recurse | Select-Object -First 1 -ExpandProperty FullName
if (!(Get-Command "gswin64.exe" -ea silent) -and ($null -eq $gsExePath)) { Write-Host "GhostScript not found. Installing..."; choco install ghostscript -y }
if ($null -eq $gsExePath) { Write-Host "Error: gswin64.exe not found, this is required by ImageMagick for PDF manipulation"; exit }
Write-Host "gswin64.exe found at '$gsExePath'"
# Add Ghostscript directory to the PATH temporarily so that ImageMagick can use it
$env:Path += ";$($gsExePath | Split-Path -Parent)"

# Create the output directory if it doesn't exist
if (-not (Test-Path $outputDirectory)) { New-Item -ItemType Directory -Force -Path $outputDirectory | Out-Null }

# Convert each page of the PDF to PNG
$imageNamePrefix = [System.IO.Path]::GetFileNameWithoutExtension($pdfFilePath)
$imageNamePrefix = $imageNamePrefix -replace '\s+', '_'

# Use ImageMagick's identify command to get the total number of pages in the PDF
$numberOfPages = (identify "$pdfFilePath" 2>$null | Measure-Object -Line).Lines
Write-Host "'$pdfFilePath' has $numberOfPages pages"
# Use ImageMagick's convert command to convert PDF
Start-Process $imageMagickExePath -ArgumentList "convert `"$pdfFilePath`" -density 600 -quality 100 -antialias -resize 300% `"$outputDirectory\$imageNamePrefix-%d.$imageExtension`"" -NoNewWindow -Wait

# Determine the maximum number of digits to normalise all page numbers to that length
$maxDigits = $numberOfPages.ToString().Length

# Normalize page numbers
for ($i = 0; $i -le $numberOfPages; $i++) {
    $pageNumber = "{0:D$maxDigits}" -f $i
    $oldFileName = Join-Path $outputDirectory "$imageNamePrefix-$i.$imageExtension"
    $newFileName = Join-Path $outputDirectory "$imageNamePrefix-$pageNumber.$imageExtension"
    if ((Test-Path $oldFileName) -and !(Test-Path $newFileName)) { Rename-Item -Path $oldFileName -NewName $newFileName }
}

# Remove the Ghostscript directory from the PATH
$env:Path = $env:Path -replace [regex]::Escape(";"+($gsExePath | Split-Path -Parent))

# command-line tools for manipulating PDFs:
# https://libgen.rs/search.php?req=pdf+hacks&lg_topic=libgen&open=0&view=simple&res=25&phrase=1&column=defs
# pdftk (PDF Toolkit): pdftk is a command-line tool for manipulating PDF files. It can merge, split, rotate, watermark, and decrypt PDF files.
# QPDF: QPDF is another command-line tool for structural, content-preserving transformation of PDF files. It's particularly useful for linearizing PDFs, decrypting, and compressing them.
# Poppler Utilities (pdftohtml, pdftotext, pdfimages): Poppler is a PDF rendering library and its utilities provide command-line tools for converting PDFs to various formats such as HTML, text, and images. pdftohtml converts PDF to HTML, pdftotext converts PDF to plain text, and pdfimages extracts images from PDFs.
# Ghostscript: Ghostscript is a suite of software based on an interpreter for Adobe Systems' PostScript and Portable Document Format (PDF) page description languages. It can be used for a wide variety of tasks including converting PDFs to various formats, merging PDFs, and more.
# MuPDF: MuPDF is a lightweight PDF, XPS, and E-book viewer. It also includes command-line tools for extracting text and images from PDFs.
# PDFMiner: PDFMiner is a tool for extracting information from PDF documents. It includes a command-line tool for extracting text, images, and other content from PDFs.
powershell
  • 1 1 respostas
  • 73 Views

1 respostas

  • Voted
  1. Best Answer
    K J
    2024-04-01T22:04:17+08:002024-04-01T22:04:17+08:00

    O método mais simples, presumindo que você deseja PNG de 300 DPI, é usar um arquivo "drop on me" .CMD ou colocar um link na pasta "SendTo". De qualquer forma, você pode exportar instantaneamente um arquivo para imagens que podem ser facilmente adaptadas para uma pasta de arquivos.

    Usando a versão 2024 de 64 bits dos binários Poppler PDFtoPPM disponíveis em https://github.com/oschwartz10612/poppler-windows

    "path to\pdftoppm.exe" -png -r 300 -aa yes -progress "%~1" "%~dpn1"
    

    insira a descrição da imagem aqui

    Portanto, este PDF de 12 páginas será exportado para a mesma pasta de trabalho.

    Para um uso mais complexo, estenda o arquivo CMD para ser executado no diretório de trabalho atual com vários arquivos e/ou subpastas.

    insira a descrição da imagem aqui

    Um comando semelhante para GhostScript poderia ser como

    "path to\bin\gswin64c" -sDEVICE=pngalpha -r300 -o"%~dpn1-%%04d.png" -f "%~1"
    

    De acordo com o comentário @KenS simplificado para 000# dígitos usando %%04d

    insira a descrição da imagem aqui

    As diferenças na saída podem ser ajustadas alterando opções adicionais, mas como os 2 comandos acima estão, o GhostScript (à esquerda abaixo) produz arquivos mais compactos.

    insira a descrição da imagem aqui

    Seguindo a postagem original, no PowerShell, para uma pasta contendo alguns PDFs, o seguinte irá percorrer e extrair os PNGs de cada PDF. Substitua os locais de pdftoppm.exe, gswin64c.exee a pasta que contém os PDFs conforme necessário. Observe que para a gswin64c.exenumeração no CMD acima, %no console fica %%dentro de um script CMD, assim como %%04dpara o script CMD, enquanto %04dfunciona no PowerShell):

    $pdftoppm = "C:\Poppler\Library\bin\pdftoppm.exe"
    $gswin64c = "C:\Program Files\gs\gs10.03.0\bin\gswin64c.exe"
    $pdfs = Get-ChildItem -Path "C:\0\*.pdf"
    
    foreach ($pdf in $pdfs) { 
        $pdfFullName = $pdf.FullName
        $pdfNameNoExt = [System.IO.Path]::GetFileNameWithoutExtension($pdf.Name)
        Start-Process $pdftoppm -ArgumentList "-png -r 300 -aa yes -progress `"$pdfFullName`" `"$pdfNameNoExt`"" -Wait
        Start-Process $gswin64c -ArgumentList "-sDEVICE=pngalpha -r300 -o`"$pdfNameNoExt-%04d.png`" -f `"$pdfFullName`"" -Wait
    }
    
    
    • 3

relate perguntas

  • Como colocar string variável em array no powershell?

  • Powershell e regex: lista de arquivos "backup ao salvar" do Notepad ++. Editar nome, classificar por lastwritetime

  • Adicionando cor de primeiro plano ao perfil do Powershell?

  • Não é possível ativar o Microsoft Print to PDF depois de desativado

  • Posso fazer com que este script do PowerShell aceite vírgulas?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como posso reduzir o consumo do processo `vmmem`?

    • 11 respostas
  • Marko Smith

    Baixar vídeo do Microsoft Stream

    • 4 respostas
  • Marko Smith

    O Google Chrome DevTools falhou ao analisar o SourceMap: chrome-extension

    • 6 respostas
  • Marko Smith

    O visualizador de fotos do Windows não pode ser executado porque não há memória suficiente?

    • 5 respostas
  • Marko Smith

    Como faço para ativar o WindowsXP agora que o suporte acabou?

    • 6 respostas
  • Marko Smith

    Área de trabalho remota congelando intermitentemente

    • 7 respostas
  • Marko Smith

    O que significa ter uma máscara de sub-rede /32?

    • 6 respostas
  • Marko Smith

    Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows?

    • 1 respostas
  • Marko Smith

    O VirtualBox falha ao iniciar com VERR_NEM_VM_CREATE_FAILED

    • 8 respostas
  • Marko Smith

    Os aplicativos não aparecem nas configurações de privacidade da câmera e do microfone no MacBook

    • 5 respostas
  • Martin Hope
    Vickel O Firefox não permite mais colar no WhatsApp web? 2023-08-18 05:04:35 +0800 CST
  • Martin Hope
    Saaru Lindestøkke Por que os arquivos tar.xz são 15x menores ao usar a biblioteca tar do Python em comparação com o tar do macOS? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh Como posso reduzir o consumo do processo `vmmem`? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Pesquisa do Windows 10 não está carregando, mostrando janela em branco 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    andre_ss6 Área de trabalho remota congelando intermitentemente 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney Por que colocar um ponto após o URL remove as informações de login? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca Todos os meus complementos do Firefox foram desativados repentinamente, como posso reativá-los? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK É possível criar um código QR usando texto? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 Altere o nome da ramificação padrão do git init 2019-04-01 06:16:56 +0800 CST

Hot tag

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve