Powershell脚本,使用Ghostscript将PDF转换为TIFF

时间:2014-03-18 13:34:02

标签: pdf powershell ghostscript

我被要求编写一个脚本,自动将PDF文件转换为TIFF文件,以便进一步处理它们。借助Google和本网站的大量帮助。 (我从未研究过任何编程语言)我在下面创建了代码。 即使它现在正在工作,但它并不是我所希望的,因为它每次运行时都会创建13个文件,它应该只创建1个文件。

有人能够好好看看剧本并告诉我哪里出错了吗?

提前谢谢!

编辑: 在这个(测试)的情况下,文件夹中只有一个PDF,它名为test.pdf,但是这个想法是脚本查看给定文件夹中的所有PDF,因为它是不确定在任何给定时间文件夹中有多少PDF。让它作为服务在后台运行(?)

我会在找到如何获取错误代码/说明后编辑帖子,我无法跟上命令行。

#Path to your Ghostscript EXE
$tool = 'C:\\Program Files\\gs\\gs9.10\\bin\\gswin64c.exe'

#Directory containing the PDF files that will be converted
$inputDir = 'C:\\test\\'

#Output path where converted PDF files will be stored
$outputDirPDF = 'C:\\test\\oud\\'

#Output path where the TIF files will be saved
$outputDir = 'C:\\test\\TIFF'

$pdfs = get-childitem $inputDir -recurse | where {$_.Extension -match "pdf"}

foreach($pdf in $pdfs)
{

    $tif = $outputDir + $pdf.BaseName + ".tif"
    if(test-path $tif)
    {
        "tif file already exists " + $tif
    }
    else        
    {   
        'Processing ' + $pdf.Name        
        $param = "-sOutputFile=$tif"
        & $tool -q -dNOPAUSE -sDEVICE=tiffg4 $param -r300 $pdf.FullName -c quit
    }
    Move-Item $pdf $outputDirPDF
}

2 个答案:

答案 0 :(得分:2)

它现在正在工作,显然我错过了一个"退出"在代码的最后。它可能不是最美丽的代码,但它似乎可以完成这项工作,所以我很满意它。 在实际工作的代码下面;

#Path to your Ghostscript EXE
$tool = 'C:\\Program Files\\gs\\gs9.10\\bin\\gswin64c.exe'

#Directory containing the PDF files that will be converted
$inputDir = 'C:\\test\\'

#Output path where converted PDF files will be stored
$outputDirPDF = 'C:\\test\\oud\\'

#Output path where the TIF files will be saved
$outputDir = 'C:\\test\\TIFF\\'

$pdfs = get-childitem $inputDir -recurse | where {$_.Extension -match "pdf"}

foreach($pdf in $pdfs)
{
    $tif = $outputDir + $pdf.BaseName + ".tif"
    if(test-path $tif)
    {
        "tif file already exists " + $tif
    }
    else        
    {   
        'Processing ' + $pdf.Name        
        $param = "-sOutputFile=$tif"
        & $tool -q -dNOPAUSE -sDEVICE=tiffg4 $param -r300 $pdf.FullName -c quit
    }
    Move-Item $pdf $outputDirPDF
}
EXIT

答案 1 :(得分:0)

它似乎为源目录中的每个PDF文件创建一个TIFF文件。目录(和任何子目录)中有多少PDF文件?输入PDF文件中有多少页?

我注意到您从' InputDir'移动了原始PDF。到' OutputDirPDF'完成后,但是' OutputDirPDF'是InputDir'的孩子,所以如果你在查找输入文件时递归子目录,你可能会找到你已经处理过的文件。 NB我对Powershell一无所知,所以这可能没问题。

我建议制作' InputDir'和' OutputDirPDF'在同一级别,例如" c:\ temp \ input"和" c:\ temp \ outputPDF"。

关于我在这里所说的所有信息,您可以说明输入的PDF文件名和输出文件名是什么,以及处理消息的内容。

相关问题