software:pdfprocessing:pdf2tif_300dpi
Table of Contents
pdf2tif_300dpi
Please see for the source code below.
Installation
The program has been written for and tested on a Microsoft Windows XP system with the script language autoit3. In order to function it needs to cooperate with a few other applications, which need to be installed as well. These are Ghostscript and ImageMagick.
NB 1. Microsoft Visual C++ 2008 SP1 should be installed due to incompatibility issues with the script.
NB 2. During installation of ImageMagick you have to enable manually the option “Install ImageMagickObject: OLE Control for VBscript, Visual Basic, and WSH.”
Download and install following files:
- Ghostscript: http://www.auditeon.com/xyz/projects/gs856w32.exe
- Microsoft Visual C++ 2008 SP1: search there for vcredist_x86.exe1)
- ImageMagick: ImageMagick
Once all files have been downloaded and installed, finally download:
- The application pdf2tif_300dpi: pdf2tif_300dpi.exe
- Either use drag and drop with your (single) pdf file onto the exe, or add the file as argument.
Source code
Please note: the code is as is. No warranty is given, nor any support.
; pdf2tif_300dpi, simple extract pdf to tiff accurately for further processing ; Copyright (C) Februari 2010 by Marc Nijdam ; ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/> ; ; Contact details: http://www.nijdam.de/marc.html ; #requireadmin ; This program should have proper rights to start external applications. Presumably this behaviour requires user admin rights #include <Constants.au3> ; Used for registry constants like REG_SZ, REG_DWORD etc. #include <Process.au3> #include <file.au3> #include <GUIConstantsEx.au3> #include <EditConstants.au3> #include <Math.au3> #Include <String.au3> Const $ThisProgramVersion = "0.3" ; Current release of this software Const $ThisProgramName = "pdf2tif" ; full filename without spaces and without exe extension ; Dependencies constants Const $Ghostscript_name = "gs\gs" ; unique string to search for in %PATH% whether Ghostscript is installed or not Const $Ghostscript_RegPath = "HKEY_LOCAL_MACHINE\SOFTWARE\GPL Ghostscript" ; registry path for Ghostscript Const $imagemagick_name = "imagemagick" ; unique string to search for in %PATH% whether ImageMagick is installed or not Const $imagemagick_RegPath = "HKEY_LOCAL_MACHINE\SOFTWARE\ImageMagick\Current" ; registry path for ImageMagick ; Requires Imagemagick installation from http://www.imagemagick.org (See over there. Choose the dynamic, 16 bit images version) ; Path environment variable should be pointing to imagemagick, (default installation will add this to the %PATH% environment variable, which is persistant) ; If not there, this script adds the following temporarily: %PROGRAMFILES%\imagemagick ; ; This program requires Ghostscript, which may be installed through Photoscore. (change xx with your version) ; Path environment variable should be pointing to: %PROGRAMFILES%\gs\gs8.xx\bin;%PROGRAMFILES%\gs\gs8.xx\lib ; ; This solve a R6034 (AutoIt3 related) error: ; http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2 ; ; Nb.: ; Write an environment variable: EnvSet ( "envvariable" [, "value"] ) ; ControlClick($parentWindowName,"ViewPages", ,2, 12, 81) ; $CmdLine[0] = number of parameters ; $CmdLine[1] = first parameter ; Current temporary filename: pdf2tif00000_etcetera ; Error constants Const $_ERROR_MissingImageMagickObject = -1 Const $_ERROR_PdfInputFileIsNotValid = -2 Const $_ERROR_ShowHelp = -3 Const $_ERROR_PdfImageSizeTooLarge = -4 Const $_ERROR_CannotFindGhostscript = -5 Const $_ERROR_imagemagickNotInstalled = -6 Const $_ERROR_MSVisualCPlusPlus2008RedistNotInstalled = -7 Const $_ERROR_PDF_FileInconsistent = -8 ; Gui constants Const $Gui_Title = $ThisProgramName Dim $nEdit ; tif and pdf constants Const $resolution = FindResolution(@ScriptName) ; Extract resolution from scriptfile name. All Files and all pages within a batch should have the same resolution. Const $rastering = 72 ; PDF rastering value Const $img_width = ($resolution/3)*(2480/100); 2480 for a4, constant in pixels, defining what the page width may be at most when portrait modus is used Const $img_height = ($resolution/3)*(3508/100) ; 3508 for a4, constant in pixels, defining what the page height may be at most when portrait modus is used Const $pdfdims[2] = [String(Int(($rastering*$img_width/$resolution)+0.5)),String(Int(($rastering*$img_height/$resolution)+0.5))] ; Array holding pdf rastering sizes a4 should be 595x842 Const $bitmaperror = int($resolution/300) ; To compensate for apparant errors during rasterization of pdf files with ghostscript, a deviation of 1 pixel per 300 dpi will use some quantization Const $tif = ".tif" ; File extensie voor tif files Const $ps = ".ps" ; File extensie voor ps files Const $pdf = ".pdf" ; File extensie voor pdf files ; program specific constants Const $Delay=400 ; Short waiting time necessary to retreive console output. Const $tempname = @TempDir & "\" & $ThisProgramName & String(StringFormat("%05s", @AutoItPID )) ; Unique name for temporary files Const $QQ = '"' Dim $szDrive, $szDir, $szFName, $szExt Dim $i , $j, $k ; ###################################################################################################### ; # main ; ###################################################################################################### CheckAndSetEnv() ; Check dependencies and set environment variables GarbageControl($ThisProgramName) ; Cleanup temporary files in $TempDir, but only if no other instances of this program are running. ; Iterate through all via the command line or per 'drag and drop' supplied files Const $NumberOfFiles = CountNumberOfFiles($CmdLine[0]) ; Count and Check whether there are any files supplied $nEdit = CreateGUI($ThisProgramName) ; Create window with info Dim $CurrentFile Dim $TotalPages ; Counted pdf pages for each document For $i = 1 to $NumberOfFiles $CurrentFile = CurrentFile($i) ; Use function to enable -during debugging- a preset file when no file is supplied GUICtrlSetData($nEdit, "###### Processing file " & String($i) & " of " & String($NumberOfFiles) & " ######" & @CRLF, 1) GUICtrlSetData($nEdit, "Current file: " & RemovePath($CurrentFile) & @CRLF & @CRLF, 1) GUICtrlSetData($nEdit, "Analyzing document..." & @CRLF, 1) $TotalPages = Number(CountPdfPages($CurrentFile,$tempname)) If $TotalPages == 0 Then GUICtrlSetData($nEdit, "->Found 0 pages, skipping this file." & @CRLF & @CRLF, 1) Else GUICtrlSetData($nEdit, "->Found " & $TotalPages & " Page(s)" & @CRLF, 1) For $j = 1 to $TotalPages GUICtrlSetData($nEdit, "-->Extracting page " & String($j) & " out of " & String($TotalPages) & @CRLF, 1) ExtractPageAsTifgray($CurrentFile, $j, $resolution) ; Convert single pdf page to tif, retreive page dimensions Next EndIf Next Exit ; ###################################################################################################### ; # Below are functions ; ###################################################################################################### ; ; Return file to process. When not compiled, return a here below set file. Func CurrentFile(Const $ArgIndex) If @Compiled == 1 Then Return $CmdLine[$ArgIndex] ; @Compiled is 1 if script is a compiled executable ; Return "test_GS_NotA4_IM_AlmostA4.pdf" ; Return "a4_2480x3508BWtest.pdf" ; Return "test_4_pages_oversized_grey.pdf" ; Return "test_size-error-2481x3507.pdf" ; Return "test_2_pages_landscape.pdf" ; Return "test_4_pages_oversized_grey.pdf" ; Return "buggyfile_2pages_instead_of_18pages.pdf" Return "test_largeBW.pdf" EndFunc ; Convert accurately a single page from a pdf file into a bitmap tif ; For each page: ; GS_Get_PDF_BoundingBoxes() ; BoundingBox=[lower left x, lower left y, upper right x, upper right y] ; if not available, get [0,0,0,0] ; HiResBoundingBox=[lower left x, lower left y, upper right x, upper right y] ; if not available, get [0,0,0,0] ; When gswin32c outputs error text, indicate with 1, otherwise 0 ; ; A4Quantization=False ; If HiResBoundingBox(lower left x + upper right x, lower left y + upper right y) < BoundingBox(lower left x + upper right x, lower left y + upper right y) Then ; If -1 < Pixel Error < 1 Then ; A4Quantization=True ; EndIf ; Else ; gswin32c -sDEVICE=tiffgray -r300 -dNOPAUSE -dQUIET -dBATCH -dAutoFilterGrayImages=false -dGrayImageFilter=/LZWEncode -dFirstPage=1 -dLastPage=1 -sOutputFile=output.tif input ; IM_Get_Image_Dimension() ; If -1 < Pixel Error < 1 Then ; If IM_Get_PDF_BoundingBox() == 595x842 OR IM_Get_PDF_BoundingBox() == 842x595 Then ; A4Quantization=True ; EndIf ; EndIf ; EndIf ; If A4Quantization=True Then ; gswin32c -sDEVICE=tiffg4 -r300 (-g2480x3508|-g3508x2480) -dMaxStripSize=8192 -dFirstPage=1 -dLastPage=1 -sOutputFile=output.tif input ; EndIf ; Return this_page.pdf Func ExtractPageAsTifgray(Const $CurrentFile, Const $j, Const $resolution) Local $outfile = UniqueFileName(StripExtension($CurrentFile) & "_" & String($j) & $tif) Local $GSResults[9], $IMDims[2] Local $x, $y, $xx, $yy, $quantize, $command Local $pagedims[2] ; String holding page dimensions. With a4 at 300 dpi, it is 2480x3508, with landscape 3508x2480 $GSResults = GS_Get_PDF_BoundingBoxes($Currentfile, $j, $resolution); Array holding page dimensions from Ghostscript bbox command and error flag If $GSResults[8] Then ShowError($_ERROR_PDF_FileInconsistent) ; If ghostscript threw an error, maybe not all pages can be retreived. Stopping now is the best option. ; Check for portrait or landscape orientation. If ($GSResults[0] + $GSResults[2]) < ($GSResults[1] + $GSResults[3]) Then $pagedims[0] = $img_width ; page is portrait $pagedims[1] = $img_height Else $pagedims[0] = $img_height ; page is landscape $pagedims[1] = $img_width EndIf ; Check if quantization with 1 pixel necessary If ($GSResults[4] + $GSResults[6]) < ($GSResults[0] + $GSResults[2]) AND _ ; Adding [4] + [6] is not what you would expect when calculating dimensions with coordinates ($GSResults[5] + $GSResults[7]) < ($GSResults[1] + $GSResults[3]) Then ; But either GS or IM is wrong in this. For now it gives accurate results of the page size $x = int($resolution/$rastering * ($GSResults[4] + $GSResults[6])+0.5) ; Width in pixels $y = int($resolution/$rastering * ($GSResults[5] + $GSResults[7])+0.5) ; height in pixels $xx = _Min($x,$y) ; shortest side of image $yy = _Max($x,$y) ; widest side of image If $xx >= ($img_width-$bitmaperror) AND $xx <= ($img_width+$bitmaperror) AND _ ; 1 pixel error at 300 dpi between 2479 and 2481 pixels. $yy >= ($img_height-$bitmaperror) AND $yy <= ($img_height+$bitmaperror) Then $quantize = True $Command = "gswin32c " & _ ; convert file to tif, Mind that you should correct the pixel aspect ratio, which is not shown properly within PSCS4 "-sDEVICE=tiffgray" & " " & _ "-r" & String($resolution) & " " & _ "-g" & String($pagedims[0]) & "x" & String($pagedims[1]) & " " & _ "-dBATCH" & " " & _ "-dNOPAUSE" & " " & _ "-dQUIET" & " " & _ "-dAutoFilterGrayImages=false" & " " & _ "-dGrayImageFilter=/LZWEncode" & " " & _ "-dFirstPage=" & Number($j) & " " & _ "-dLastPage=" & Number($j) & " " & _ "-sOutputFile=" & $QQ & $outfile & $QQ & " " & _ $QQ & $CurrentFile & $QQ RunWait(@ComSpec & " /c " & $Command, @ScriptDir, @SW_HIDE) EndIf EndIf If Not $quantize Then $Command = "gswin32c " & _ ; convert file to tif. Use grayscale: If size exceeds a4, then additonal high quality resizing will be necessary "-sDEVICE=tiffgray" & " " & _ "-r" & String($resolution) & " " & _ "-dBATCH" & " " & _ "-dNOPAUSE" & " " & _ "-dQUIET" & " " & _ "-dAutoFilterGrayImages=false" & " " & _ "-dGrayImageFilter=/LZWEncode" & " " & _ "-dFirstPage=" & Number($j) & " " & _ "-dLastPage=" & Number($j) & " " & _ "-sOutputFile=" & $QQ & $outfile & $QQ & " " & _ $QQ & $CurrentFile & $QQ RunWait(@ComSpec & " /c " & $Command, @ScriptDir, @SW_HIDE) EndIf $IMDims = IM_Get_Dims($outfile) If Not $quantize Then $x = $IMDims[0] ; Width in pixels $y = $IMDims[1] ; height in pixels $xx = _Min($x,$y) ; shortest side of image $yy = _Max($x,$y) ; widest side of image If $xx >= ($img_width-$bitmaperror) AND $xx <= ($img_width+$bitmaperror) AND _ ; 1 pixel error at 300 dpi between 2479 and 2481 pixels wide. $yy >= ($img_height-$bitmaperror) AND $yy <= ($img_height+$bitmaperror) Then $quantize = True $Command = "gswin32c " & _ ; convert file to tif "-sDEVICE=tiffgray" & " " & _ "-r" & String($resolution) & " " & _ "-g" & String($pagedims[0]) & "x" & String($pagedims[1]) & " " & _ ; apparently pages with real sizes of 2481x3507 cannot be forced to 2480x3508 format "-dBATCH" & " " & _ "-dNOPAUSE" & " " & _ "-dQUIET" & " " & _ "-dAutoFilterGrayImages=false" & " " & _ "-dGrayImageFilter=/LZWEncode" & " " & _ "-dFirstPage=" & Number($j) & " " & _ "-dLastPage=" & Number($j) & " " & _ "-sOutputFile=" & $QQ & $outfile & $QQ & " " & _ $QQ & $CurrentFile & $QQ RunWait(@ComSpec & " /c " & $Command, @ScriptDir, @SW_HIDE) EndIf EndIf EndFunc ; find the pdf HiResBoundingBox with ghostscript. GS String: gswin32c -sDEVICE=bbox -dQUIET -dNOPAUSE -dBATCH file Func GS_Get_PDF_BoundingBoxes(Const $PDFFile, Const $j, Const $resolution) Local $line, $GSResult[9], $Command, $Result = "" $Command = "gswin32c.exe " & _ "-sDEVICE=bbox" & " " & _ ; Ghostview command to get details like HiResBoundingBox "-dQUIET" & " " & _ "-dNOPAUSE"& " " & _ "-dBATCH" & " " & _ "-dFirstPage=" & Number($j) & " " & _ "-dLastPage=" & Number($j) & " " & _ $QQ & $PDFFile & $QQ Local $console = Run(@ComSpec & " /c " & $Command, @ScriptDir, @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD) While 1 Sleep($Delay) $line = StderrRead($console) If @error Then ExitLoop $Result = $line WEnd $GSResult[0] = Number(StringRegExpReplace($Result, '(?s)%%BoundingBox:[\s]*([\d]+)[\s]+([\d]+)[\s]+([\d]+)[\s]+([\d]+)(.*)', '$1')) $GSResult[1] = Number(StringRegExpReplace($Result, '(?s)%%BoundingBox:[\s]*([\d]+)[\s]+([\d]+)[\s]+([\d]+)[\s]+([\d]+)(.*)', '$2')) $GSResult[2] = Number(StringRegExpReplace($Result, '(?s)%%BoundingBox:[\s]*([\d]+)[\s]+([\d]+)[\s]+([\d]+)[\s]+([\d]+)(.*)', '$3')) $GSResult[3] = Number(StringRegExpReplace($Result, '(?s)%%BoundingBox:[\s]*([\d]+)[\s]+([\d]+)[\s]+([\d]+)[\s]+([\d]+)(.*)', '$4')) $GSResult[4] = Number(StringRegExpReplace($Result, '(?s).*HiResBoundingBox:.*\s(\d+\.\d+).*\s(\d+\.\d+).*\s(\d+\.\d+).*\s(\d+\.\d+).*', '$1')) $GSResult[5] = Number(StringRegExpReplace($Result, '(?s).*HiResBoundingBox:.*\s(\d+\.\d+).*\s(\d+\.\d+).*\s(\d+\.\d+).*\s(\d+\.\d+).*', '$2')) $GSResult[6] = Number(StringRegExpReplace($Result, '(?s).*HiResBoundingBox:.*\s(\d+\.\d+).*\s(\d+\.\d+).*\s(\d+\.\d+).*\s(\d+\.\d+).*', '$3')) $GSResult[7] = Number(StringRegExpReplace($Result, '(?s).*HiResBoundingBox:.*\s(\d+\.\d+).*\s(\d+\.\d+).*\s(\d+\.\d+).*\s(\d+\.\d+).*', '$4')) $GSResult[8] = StringRegExp($Result, '(?s).*error.*') Return $GSResult EndFunc ; find the image dimensions with imagemagick: identify -format "%[fx:w]x%[fx:h]" Func IM_Get_Dims(Const $CurrentFile) Local $line, $this_dims[2], $Result = "" Local $Command = "identify " & _ $QQ & "-format" & $QQ & " " & _ ; Ghostview command to get details like HiResBoundingBox $QQ & "%[fx:w]x%[fx:h]" & $QQ & " " & _ ; ImageMagick command to find page dimensions $QQ & $CurrentFile & $QQ Local $console = Run(@ComSpec & " /c " & $Command, @ScriptDir, @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD) While 1 Sleep($Delay) $line = StdoutRead($console) If @error Then ExitLoop $Result = $line WEnd $this_dims[0] = Number(StringRegExpReplace($result, "([0-9]+)x([0-9]+)", "$1")) ; From string holding dimensions (for example "1800x1600") extract first number $this_dims[1] = Number(StringRegExpReplace($result, "([0-9]+)x([0-9]+)", "$2")) ; From string holding dimensions (for example "1800x1600") extract second number Return $this_dims EndFunc ; Count the number of supplied files and check if this program is invoked through Scite. Func CountNumberOfFiles(Const $count) If @Compiled == 0 Then Return 1 ; When invoking this program from within the Scite compiler, use some preset variables for which file to use If $count == 0 Then ShowError($_ERROR_ShowHelp) ; number of parameters Return $count EndFunc ; Extract resolution from scriptfile name with regex, if not specifically specified and less than 300 return 300 (dpi) Func FindResolution(Const $ProgramFileName) Return _Max(Number(StringRegExpReplace(@ScriptName, "(.*)(\D+)(\d+)(dpi|.*)(\.)(.*)", "$3")),300) EndFunc ; Extract file name from path Func RemovePath(Const $OutputFile) If FileExists(RemoveDoubleQuotes($OutputFile)) Then Local $szDrive, $szDir, $szFName, $szExt _PathSplit(RemoveDoubleQuotes($OutputFile), $szDrive, $szDir, $szFName, $szExt) Return $szFName & $szExt Else ShowError("Cannot find working directory") EndIf EndFunc ; This function will remove a trailing slash to a windows file path Func RemoveDoubleQuotes(Const $var) Return StringRegExpReplace($var, "^""(.*)""$","$1") EndFunc Func ModifyFileName(Const $CurrentFile) Local $szDrive, $szDir, $szFName, $szExt _PathSplit($CurrentFile, $szDrive, $szDir, $szFName, $szExt) Return $szDrive & $szDir & $szFName & "_Processed" & $szExt EndFunc ; Prevent overwriting a file, when it already exists. This function will find the 'first' free filename. Func UniqueFileName(Const $OutputFile) If FileExists(RemoveDoubleQuotes($OutputFile)) Then Local $i = 1 Local $szDrive, $szDir, $szFName, $szExt _PathSplit(RemoveDoubleQuotes($OutputFile), $szDrive, $szDir, $szFName, $szExt) While FileExists($szDrive & $szDir & $szFName & "(" & String($i) & ")" & $szExt) $i += 1 WEnd Return $szDrive & $szDir & $szFName & "(" & String($i) & ")" & $szExt Else Return $OutputFile EndIf EndFunc ; This function will add a trailing slash to a windows file path Func AddSlash(Const $var) Return StringRegExpReplace($var, "(.)\\*$","$1\\") EndFunc ; Create GUI window with console like output Func CreateGUI(Const $ThisProgramName) Const $Gui_Xpos = 140 Const $Gui_Ypos = 23 Const $Gui_Width = 518 Const $Gui_Height = 200 Const $Gui_Border = 15 Const $Gui_HeightButton = 20 Const $Gui_WidthButton = 75 Const $Gui_WidthSlider = 20 Opt("GUIOnEventMode", 1); GUI should be in OnEvent Mode, otherwise our cancelbutton event is not captured HotKeySet("{Esc}", "CancelButton"); Pressing the Escape button cancels operation GUICreate($Gui_Title,$Gui_Width,$Gui_Height,$Gui_Xpos,$Gui_Ypos) ; will create a dialog box that when displayed is centered $nEdit = GUICtrlCreateEdit ("",$Gui_Border,$Gui_Border,$Gui_Width-$Gui_Border-$Gui_WidthSlider,$Gui_Height-$Gui_Border-2*$Gui_HeightButton, BitOr($ES_AUTOVSCROLL,$ES_READONLY,$ES_MULTILINE)) GUICtrlSetBkColor($nEdit, 0xffffff) $hButton = GUICtrlCreateButton ("Cancel", ($Gui_Width-$Gui_WidthButton)/2,$Gui_Height-$Gui_HeightButton*1.5, $Gui_WidthButton, $Gui_HeightButton) GUICtrlSetOnEvent($hButton, "CancelButton") ; Function executed when cancel button is pressed GUISetState() Return $nEdit EndFunc ; Strip path and extension Func StripExtension(Const $OutputFile) If FileExists(RemoveDoubleQuotes($OutputFile)) Then Local $szDrive, $szDir, $szFName, $szExt _PathSplit(RemoveDoubleQuotes($OutputFile), $szDrive, $szDir, $szFName, $szExt) Return $szDrive & $szDir & $szFName Else ShowError("Cannot find working directory") EndIf EndFunc Func IndirectDelete(Const $Pdf_ListOfFiles2Proces) Local $Handle = FileOpen($Pdf_ListOfFiles2Proces, 0) Local $line While 1 $line = FileReadLine($Handle) If @error = -1 Then ExitLoop If FileExists($line) Then FileDelete($line) ; Delete temp file Wend FileClose($Handle) EndFunc ; Find number of PDF pages in document Func CountPdfPages(Const $CurrentFile, Const $tempname) Local $Command $Command = $QQ & $CurrentFile & $QQ & " " & _ ; Use pdf2dsc to find out the number of pages. E.g. %%Pages: 1 $QQ & $tempname & "info.dsc" & $QQ _RunDos("pdf2dsc " & $Command) $Command = OpenFileAndGrep($tempname & "info.dsc", "%%Pages:") If FileExists($tempname & "info.dsc") Then FileDelete($tempname & "info.dsc") ; Delete dsc file If Not $Command Then Return(0); The supplied file is not a pdf file, in order to skip this file, the amount of 0 pages will be returned Return(Number(StringReplace($Command, "%%Pages: ", ""))) EndFunc ; Opens a file and returns a line which contains a grep alike specified keyword Func OpenFileAndGrep(Const $OFAG_path,Const $OFAG_query) Local $OFAG_file = FileOpen($OFAG_path,0) Local $OFAG_result = FileRead($OFAG_file) FileClose($OFAG_file) If $OFAG_result = "" Then ; If string is empty, return empty string as well Return Else Local $OFAG_q = "" Local $OFAG_stdinArray = StringSplit($OFAG_result, @LF, 1) ; put read data, separated by LineFeed characters, in an array Local $OFAG_i For $OFAG_i In $OFAG_stdinArray If StringInStr($OFAG_i,$OFAG_query) Then $OFAG_q &= $OFAG_i ExitLoop EndIf Next EndIf return $OFAG_q EndFunc ; Cleanup temporary files in $TempDir, but only if no other instances of this program are running. Func GarbageControl(Const $ThisProgramName) Local $i Local $count = 0 Local $list = ProcessList() For $i = 1 to $list[0][0] If $list[$i][0] = $ThisProgramName & ".exe" Then $count = $count+1 Next If $count == 1 Then If FileExists(@TempDir & "\" & $ThisProgramName & "*") Then FileDelete(@TempDir & "\" & $ThisProgramName & "*") ; Delete temporary files EndIf EndFunc ; Check MS dependencies and set environment variables for Imagemagick, Ghostscript Func CheckAndSetEnv() If Not Find_MS_Visual_C_PlusPlus_2008_SP1_Redist() Then ShowError($_ERROR_MSVisualCPlusPlus2008RedistNotInstalled) If Not FileExists(Find_imagemagick_Path("HKEY_LOCAL_MACHINE\SOFTWARE\ImageMagick\Current","BinPath") & "\ImageMagickObject.dll") Then ShowError ($_ERROR_Need_ImageMagickObject_OLE) ; If Not FileExists(@SystemDir & "\ImageMagickObject.dll") Then FileInstall("ImageMagickObject.dll",@SystemDir&"\ImageMagickObject.dll",0) If Not EnvPathExists(Find_Ghostscript_Path($Ghostscript_RegPath,"GS_LIB")) Then SetEnvPath(Find_Ghostscript_Path($Ghostscript_RegPath,"GS_LIB")) ; Check if gs path should be added to %PATH% if it's not there already If Not EnvPathExists(Find_imagemagick_Path($imagemagick_RegPath,"BinPath")) Then SetEnvPath(Find_imagemagick_Path($imagemagick_RegPath,"BinPath")) ; Check if imagemagick path should be added to %PATH% if it's not there already ; If Not ObjectIsRegistered("HKEY_CLASSES_ROOT\ImageMagickObject.MagickImage\CurVer", "") Then RunWait(@ComSpec & " /c regsvr32 /s MagickObject.dll",@SystemDir,@SW_HIDE) EndFunc ; Find Microsoft Visual C++ 2008 SP1 Redistributable Package Func Find_MS_Visual_C_PlusPlus_2008_SP1_Redist() Local $var $var = RegRead("HKEY_CLASSES_ROOT\Installer\Products\D20352A90C039D93DBF6126ECE614057","PackageCode") If @error <> 0 Or $var == "" Then Return False Return True EndFunc ; This function makes sure that the to be added $EnvironmentVariablePath is only added once to the environment path. For this it differentiates between Ghostscript and ImageMagick Func SetEnvPath(Const $EnvVarApplication) If StringRight(EnvGet("PATH"),1) <> ";" Then EnvSet("PATH",EnvGet("PATH") & ";") ; Add a ; separator between path if it's not there already Local $i Local $SplitEnvVarApplication = StringSplit($EnvVarApplication,";") If @error == 1 Then EnvSet("PATH", EnvGet("PATH") & $EnvVarApplication) Else For $i = 1 To $SplitEnvVarApplication[0] If Not StringInStr(EnvGet("PATH"),$SplitEnvVarApplication[$i]) Then EnvSet("PATH", EnvGet("PATH") & $SplitEnvVarApplication[$i] & ";") Next EndIf EndFunc ; This function checks whether the (part of the) $EnvVarApplication already exists in the %PATH% environment. Func EnvPathExists(Const $EnvVarApplication) Local $i Local $found = True Local $SplitEnvVarApplication = StringSplit($EnvVarApplication,";") If @error == 1 Then If StringInStr(EnvGet("PATH"), $EnvVarApplication) Then Return $found ; The delimiter character ; had not been found Else For $i = 1 To $SplitEnvVarApplication[0] If Not StringInStr(EnvGet("PATH"),$SplitEnvVarApplication[$i]) Then $found=False ; One or more applications in the path had been found Next EndIf Return $found EndFunc ; Find Ghostscript Path Func Find_Ghostscript_Path(Const $Ghostscript_RegHive, Const $Ghostscript_EnvKey) Local $var Local $var_read Local $i = 1 Local $GhostscriptVersion Local $GhostscriptPath Local $GhostscriptFound = False Local $GhostscriptPathFound = False While 1 $var = RegEnumKey($Ghostscript_RegHive, $i) If @error <> 0 Then ExitLoop If StringRegExp($var,"^[0-9]+\.[0-9]+") Then $GhostscriptVersion = String($var) $GhostscriptFound = True EndIf $i += 1 WEnd $i = 1 If $GhostscriptFound Then While 1 $var = RegEnumVal($Ghostscript_RegHive & "\" & $GhostscriptVersion, $i) If @error <> 0 Then ExitLoop If $var == $Ghostscript_EnvKey Then $GhostscriptPath = RegRead($Ghostscript_RegHive & "\" & $GhostscriptVersion, $Ghostscript_EnvKey) & ";" $GhostscriptPath &= StringRegExpReplace($GhostscriptPath, "(?i)(.*)(c:\\.*)lib;.*", "$2bin") ; Add also the ghostscript bin path $GhostscriptPathFound = True ExitLoop EndIf $i += 1 WEnd EndIf If $GhostscriptPathFound Then Return $GhostscriptPath Else ShowError ($_ERROR_CannotFindGhostscript) EndIf Return EndFunc ; Find imagemagick Path Func Find_imagemagick_Path(Const $imagemagick_RegHive, Const $imagemagick_EnvKey) Local $var $var = RegRead($imagemagick_RegHive,$imagemagick_EnvKey) If @error <> 0 Or $var == "" Or StringInStr($var,$imagemagick_name) == 0 Then ShowError ($_ERROR_imagemagickNotInstalled) Return $var EndFunc ; Find if object is already registered Func ObjectIsRegistered(Const $Obj_RegHive, Const $Obj_Key) Local $var $var = RegRead($Obj_RegHive,$Obj_Key) If @error <> 0 Or $var <> "ImageMagickObject.MagickImage.1" Then Return False Return True EndFunc ; Cancel button had been pressed. A few cleanup steps should take place. Func CancelButton() GUIDelete() If FileExists($tempname & "*") Then FileDelete(AddSlash(@TempDir) & $tempname & "*") ; Delete temporary files Exit EndFunc ; Show related error, try to terminate program properly Func ShowError(Const $_ERROR_Number) Switch $_ERROR_Number ; Case $_ERROR_MissingImageMagickObject ; MsgBox(0,"Error", "ImageMagickObject cannot be registered." & _ ; "Maybe it is already registered.") Case $_ERROR_PdfInputFileIsNotValid MsgBox(0,"Error", "Supplied PDF file is invalid." & @CRLF & @CRLF & _ "Please check your pdf file.") Case $_ERROR_ShowHelp MsgBox(0,"Help", $Gui_Title & " v" & $ThisProgramVersion & @CRLF & _ "Written by Marc Nijdam, Feb. 2010" & @CRLF & @CRLF & _ "Usage:" & @CRLF & _ StringRegExpReplace(@ScriptName, "(?i)(.*)(\.)(au3|exe)(.*)", "$1$4 ") & "<inputfile1> [<inputfile 2> ... <inputfile n>]"& @CRLF & _ "[...] is optional"& @CRLF & _ "Resolution is: " & $resolution & "dpi" & @CRLF & _ "Resolution can be added optionally within the filename") Case $_ERROR_PdfImageSizeTooLarge MsgBox(0,"Error", "Image size of PDF file is too large." & @CRLF & @CRLF & _ "Processing would not make much sense.") Case $_ERROR_CannotFindGhostscript MsgBox(0,"Error", "Ghostscript is not installed." & @CRLF & @CRLF & _ "Please go to:" & @CRLF & _ "http://sourceforge.net/projects/ghostscript/" & @CRLF & @CRLF & _ "From there, download and install Ghostscript.") Case $_ERROR_imagemagickNotInstalled MsgBox(0,"Error", "ImageMagick is missing." & @CRLF & @CRLF & _ "Please go to:" & @CRLF & _ "http://www.imagemagick.org/script/binary-releases.php#windows" & @CRLF & @CRLF & _ "From there, download the Q16-windows-dll version." & @CRLF & @CRLF & _ "Make sure the installation option " & $QQ & "Install ImageMagickObject" & @CRLF & _ "OLE Control for VBscript, Visual Basic, and WSH." & $QQ & " is enabled.") Case $_ERROR_MSVisualCPlusPlus2008RedistNotInstalled MsgBox(0,"Error", "Microsoft Visual C++ 2008 SP1 is not available." & @CRLF & @CRLF & _ "Please go to:" & @CRLF & _ "http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2" & @CRLF & @CRLF & _ "From there, download and install vcredist_x86.") Case $_ERROR_PDF_FileInconsistent MsgBox(0,"Error", "The current processed pdf file contains some errors." & @CRLF & @CRLF & _ "To prevent further bad results, you could" & @CRLF & _ "try to open the file with a pdf viewer and" & @CRLF & _ "print from there to a pdf file to get a" & @CRLF & _ "new and more consistent pdf file.") Case Else MsgBox(0,"Error", "Error number: " & String($_ERROR_Number)) EndSwitch Exit EndFunc
1)
Alternatively, when not found, click here: vcredist_x86.exe
software/pdfprocessing/pdf2tif_300dpi.txt · Last modified: 2010/09/14 00:07 by admin