I'm not sure if this is the right place to post this question.
I'm trying to reduce the size of multiple 7MB PDF files so I tried this ghostscript commands I found online:
simple ghostscript with printer quality setting
gswin32c.exe -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf
tried this
gswin32c.exe -o output.pdf -sDEVICE=pdfwrite -dColorConversionStrategy=/LeaveColorUnchanged -dDownsampleMonoImages=false -dDownsampleGrayImages=false -dDownsampleColorImages=false -dAutoFilterColorImages=false -dAutoFilterGrayImages=false -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode input.pdf
and this
gswin32c.exe -o output.pdf -sDEVICE=pdfwrite -dColorConversionStrategy=/LeaveColorUnchanged -dEncodeColorImages=false -dEncodeGrayImages=false -dEncodeMonoImages=false input.pdf
but in all cases the PDF files obtained were 'bigger' that the original.
All these pdf files are basically a collection of scanned images so maybe I need a specific option to 'tell' ghostscript to compress them ?
The strange thing I found is that using the trial version of phantom pdf I was able to reduce the size to 2-5MB without visible loss of quality.
How do I do the same with ghostscript ?
Firstly, Ghostscript (or more accurately, Ghostscript's pdfwrite device) doesn't 'shrink' PDF files, it makes new ones which may, or may not, be smaller.
Secondly, its practically impossible to say what might be happening with a PDF file without an example to look at.
If your files really are scanned images, then (assuming sensible initial compression) there's probably no way to reduce the file size without reducing quality. You might not notice the reduction in quality, especilaly if you're just viewing on screen, but it will be there.
Random poking with command lines which you run across online is probably not going to result in useful output either; you really need to understand where the size is being used in your original files, and then select options which are likely to reduce that.
For example, you say the pages are scanned images; there are only two realistic ways to reduce the size of an image, downsample it to a lower resolution, or select a different (more efficient, possibly lossy, compression). Ghostscript already compresses image data (unless you tell it not to).
The latter two of your command lines explicitly disable image downsampling, so they are not likely to reduce the size of scanned images. (by default the pdfwrite device doesn't downsample images, we try to preserve quality)
The middle option disables auto compression, and selects Flate compression. If your images were previously JPEG compressed, or are not contone images, then this is probably reasonable.
You also say that the PDF files got larger, most likely this is due to using compressed object streams and xref, which is a PDF 1.5 feature that the pdfwrite device doesn't support. However its not likely to save you much space.
I'd say the most likely difference is that 'phantom PDF' is using more aggressive downsampling, which you could reproduce with pdfwrite.
I'm assuming, of course, that you are using a recent version of Ghostscript. Older versions unsurprisingly perform less well than recent ones.
Related
I have lots of PDF documents which take a lot space in the DB because they are scans of text documents with handwritten annotations. Each page is actually a JFIF image.
I tried a command from a similar SO question which resulted in a considerable gain in size (11Mb to 1Mb) but also a considerable loss of quality as the text becomes very blury and hard to read:
gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dPDFSETTINGS=/screen -dCompatibilityLevel=1.4 -dEncodeColorImages=true -sOutputFile=/tmp/document-1.pdf /tmp/document.pdf
How do I reduce the size of a my PDF with minor loss of quality ?
From here : https://stackoverflow.com/a/50018211/8315843
gs -dBATCH -dNOPAUSE -sDEVICE=pdfimage8 -r150 -sOutputFile=/tmp/document-1.pdf /tmp/document.pdf
The profile 'ebook' also uses the resolution of 150dpi among lots of other parameters :
gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -sOutputFile=/tmp/document-1.pdf /tmp/document.pdf
Or you could try k2pdfopt.
k2pdfopt -mode copy.
It sticks to older compression algorithms, because of compatibility constraints, so it may increase pdf file size, but it usually reduces pdf fie size and almost always reduces loading time.
I am writing this answer because I also searched a lot for a oneliner that would allow me to downscale the scanned images and set the DPI of the resulting pdf.
The answer from Sybuser is correct and will produce the wanted effect, but I was looking for something more than a predefined list of SETTINGS.
This is the resource I recommend: follow link to understand what possibilities are offered by GhostScript.
I used the following combination of switches:
gs -sDEVICE=pdfimage8 -dDownScaleFactor=2 -r150 -q -o output.pdf Clopotele-Hemingway.pdf
to reduce 9 pages of a scanned book from 2.3 M :
down to 660 K:
Original
"Compressed" (pdfimage8 dDownScaleFactor=2 DPI: 150
All the necessary details and more you can find at the official documentation of GhostScript, by experimenting with the three switches, you can tune in to a setting that best suits your needs:
-sDEVICE=pdfimage8
-dDownScaleFactor=2
-r150
Happy compressing!
I have no experience of programming.
My PDFs won't display images on the iPad in PDFExpert or GoodNotes as the images are in JPEG2000, from what I could find on the internet.
These are large PDFs, upto 1500-2000 pages with images. One of these was an 80MB or so file. I tried printing it with Foxit to convert the images to JPG from JPEG2000 but the file size jumped to 800MB...plus it's taking too long.
I stumbled upon Ghostscript, but I have NO clue how to use the command line interface.
I am very short on time. Pretty much need a step by step guide for a small script that converts all my PDFs in one go.
Very sorry about my inexperience and helplessness. Can someone spoon-feed me the steps for this?
EDIT: I want to switch the JPEG2000 to any other format that produces less of an increase in file size and causes a minimal loss in quality (within reason). I have no clue how to use Ghostscript. I basically want to change the compression on the images to something that will display correctly on the iPad while maintaining the quality of the rest of the text, as well as the embedded bookmarks.
I'll repeat that I have NO experience with command line...I don't even know how to point GS to the folder my PDFs are in...
You haven't really said what it is you want. 'Convert' PDFs how exactly ?
Note that switching from JPX (JPEG2000) to JPEG will result in a quality loss, because the image data will be quantised (with a different quantisation scheme to JPX) by the JPEG encoder. You can use a lossless compression scheme instead, but then you won't get the same kind of compression. You won't get the same compression ratio as JPX anyway no matter what you use, the result will be larger.
A simple Ghostscript command would be:
gs -sDEVICE=pdfwrite -o out.pdf in.pdf
Because JPEG2000 encoding is (or at least, was) patent encumbered, the pdfwrite device doesn't write images as JPX< by default it will write them several times with different compression schemes, and then use the one that gives the best compression (practically always JPEG).
Getting better results will require more a complex command line, but you'll also have to be more explicit about what exactly you want to achieve, and what the perceived problem with the simplistic command line is.
[EDIT]
Well, giving help on executing a command line is a bit off-topic for Stack Overflow, this is supposed to be a site for software developers :-)
Without knowing what operating system you are using its hard to give you detailed instructions, I also have no idea what an iPad uses, I don't generally use Apple devices and my only experience is with Macs.
Presumably you know where (the directory) you installed Ghostscript. Either open a command shell there and type the command ./gs or execute the command by giving the full path, such as :
/usr/bin/gs
I thought the arguments on the command line were self-explanatory, but....
The -sDEVICE=pdfwrite switch tells Ghostscript to use the pdfwrite device, as you might guess from the name, that device writes PDF files as its output.
The -o switch is the name (and full path if required) of the output file.
The final argument is the name (and again, full path if its not in the current directory) of the input file.
So a command might look like:
/usr/bin/gs -sDEVICE=pdfwrite -o /home/me/output.pdf /home/me/input.pdf
Or if Ghostscript and the input file are in the same directory:
./gs -sDEVICE=pdfwrite -o out.pdf input.pdf
I am trying to convert a multi-page PDF file into a bunch of JPEGs, one for each page in the PDF. I have spent hours and hours looking up how to do this, and eventually I discovered that I need Ghostscript installed. So I did that (from this website: http://downloads.ghostscript.com/public/ And I used the most recent link "ghostscript-9.05.tar.gz" from Feb 8, 2012).
However, even with this installed/downloaded, I am still unable to do what I want. Should I have this saved somewhere special, like in the same folder as ImageMagick?
What I have figured out so far is this:
In Command Prompt I change the working directory to the ImageMagick folder, where that is saved.
I then type
convert "<full file path to pdf>" "<full file path to jpg>"
This is followed by a giant blob of error. It begins with:
Unrecoverable error: rangecheck in.setuserparams
Operand stack:
Followed by a blurb of unreadable numbers and caps. It ends with:
While reading gs_lev2.ps:
%%[ Error: invalidaccess; OffendingCommand: put ]%%
Needless to say, after hours and hours of deliberation, I don't think I am any closer to doing the seemingly simple task of converting this PDF into a JPG.
What I would like are some step by step instructions on how to make this work. Don't leave out anything, no matter how "obvious" it might seem (especially anything involving ghostscript). This has been troubling me and my supervisor for months now.
For further clarification, we are on a Windows XP operating system. The eventual intention is to call these command lines in R, the statistical language, and run it in a script. In addition, I have been able to successfully convert JPGs to PNG format and vice versa, but PDF just is not working.
Help!!!
You don't need ImageMagick for this, Ghostscript can do it all alone. (If you used ImageMagick, it couldn't do that conversion itself, it HAS to use Ghostscript as its 'delegate'.)
Try this for directly using Ghostscript:
c:\path\to\gswin32c.exe ^
-o page_%03d.jpg ^
-sDEVICE=jpeg ^
d:/path/to/input.pdf
This will create a new JPEG for each page, and the filenames will increment as page_001.jpg, page_002.jpg,...
Note, this will also create JPEGs which use all the default settings of the jpeg device (one of the most important ones will be that the resolution will be 72dpi).
If you need higher (or lower resolution) for your images, you can add other options:
gswin32c.exe ^
-o page_%03d.jpg ^
-sDEVICE=jpeg ^
-r300 ^
-dJPEGQ=100 ^
d:/path/to/input.pdf
-r300 sets the resolution to 300dpi and -dJPEGQ=100 sets the highest JPEG quality level (Ghostscript's default is 75).
Also note, please: JPEG is not well suited to represent shapes with sharp edges and high contrast in good quality (such as you typically see in black-on-white text pages with small characters).
The (lossy) JPEG compression method is optimized for continuous-tone pictures + photos, and not for line graphics. Therefore it is sub-optimal for such PostScript or PDF input pages which mainly contain text. Here, the lossy compression of the JPEG format will result in poorer quality output even if the input is excellent. See also the JPEG FAQ for more details on this topic.
You may get better image output by choosing PNG as the output format (PNG uses a lossless compression):
gswin32c.exe ^
-o page_%03d.png ^
-sDEVICE=png16m ^
-r150 ^
d:/path/to/input.pdf
The png16m device produces 24bit RGB color. You could swap this for pnggray (for pure grayscale output), png256 (for 8-bit color), png16 (4-bit color), pngmono (black and white only) or pngmonod (alternative black-and-white module).
There are numerous SaaS services that will do this for you too. HyPDF and Blitline come to mind.
I have a 100 page PDF that is about 50 MBs. I am running the script below against it and it's taking about 23 seconds per page. The PDF is a scan of a paper document.
gswin32.exe -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.3
-dPDFSETTINGS=/screen -sOutputFile=out4.pdf 09.pdf
Is there anything I can do to speed this up? I've determined that the -dPDFSettings=/screen is what is making it so slow, but i'm not getting good compression without it...
UPDATE:
OK I tried updating it to what I have below. Am i using the -c 30000000 setvmthreshold portion correctly?
gswin32.exe -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.3
-dPDFSETTINGS=/screen -dNumRenderingThreads=2 -sOutputFile=out7.pdf
-c 30000000 setvmthreshold -f 09.pdf
If you are on a multicore system, make it use multiple CPU cores with:
-dNumRenderingThreads=<number of cpus>
Let it use up to 30mb of RAM:
-c "30000000 setvmthreshold"
Try disabling the garbage collector:
-dNOGC
Fore more details, see Improving Performance section from Ghoscript docs.
I was crunching a ~300 page PDF on a core i7 and found that adding the following options provided a significant speedup:
%-> comments to the right
-dNumRenderingThreads=8 % increasing up to 64 didn't make much difference
-dBandHeight=100 % didn't matter much
-dBandBufferSpace=500000000 % (500MB)
-sBandListStorage=memory % may or may not need to be set when gs is compiled
-dBufferSpace=1000000000 % (1GB)
The -c 1000000000 setnvmthreshold -f thing didn't make much difference for me, FWIW.
You don't say what CPU and what amount of RAM your computer is equipped with.
Your situation is this:
A scanned document as PDF, sized about 500 kB per page on avarage. That means each page basically is a picture, using the scan resolution (at least 200 dpi, maybe even 600 dpi).
You are re-distilling it with Ghostscript, using -dPDFSETTINGS=/screen. This setting will do quite a few things to make the file size smaller. Amongst the most important are:
Re-sample all (color or grayscale) images to 72dpi
Convert all colors to sRGB
Both these operations can quite "expensive" in terms of CPU and/or RAM usage.
BTW, your setting of -dCompatibilityLevel=1.3 is not required; it's already implicitely set by -dPDFSETTINGS=/screen already.
Try this:
gswin32.exe ^
-o output.pdf ^
-sDEVICE=pdfwrite ^
-dPDFSETTINGS=/screen ^
-dNumRenderingThreads=2 ^
-dMaxPatternBitmap=1000000 ^
-c "60000000 setvmthreshold" ^
-f input.pdf
Also, if you are on a 64bit system, try to install the most recent 32bit Ghostscript version (9.00). It performs better than the 64bit version.
Let me tell you that downsampling a 600dpi scanned page image to 72dpi usually does not take 23 seconds for me, but less than 1.
To speed up rasterizing a pdf with large bitmap graphics to a high-quality 300 ppi png image, I found that setting -dBufferSpace as high as possible and -dNumRenderingThreads to as many cores as available was the most effective for most files, with -dBufferSpace providing the most significant lift.
The specific values that worked the best were:
-dBufferSpace=2000000000 for 2 gigabytes of buffer space. This took the rasterization of one relatively small file from 14 minutes to just 50 seconds. For smaller files, there wasn't much difference from setting this to 1 gigabyte, but for larger files, it made a significant difference (sometimes 2x faster). Trying to go to 3 gigabytes or above for some reason resulted in an error on startup "Unrecoverable error: rangecheck in .putdeviceprops".
-dNumRenderingThreads=8 for a machine with 8 cores. This took the rasterization of that same file from 14 minutes to 4 minutes (and 8 minutes if using 4 threads). Combining this with the -dBufferSpace option above took it from 50 seconds to 25 seconds. When combined with -dBufferSpace however, there appeared to be diminishing returns as the number threads were increased, and for some files there was little effect at all. Strangely for some larger files, setting the number of threads to 1 was actually faster than any other number.
The command overall looked like:
gs -sDEVICE=png16m -r300 -o document.png -dNumRenderingThreads=8 -dBufferSpace=2000000000 -f document.pdf
This was tested with Ghostscript 9.52, and came out of testing the suggestions in #wpgalle3's answer as well as the Improving performance section in the Ghostscript documentation.
A key takeaway from the documentation was that when ghostscript uses "banding mode" due to the raster image output being larger than the value for -dMaxBitmap, it can take advantage of multiple cores to speed up the process.
Options that were ineffective or counterproductive:
Setting -c "2000000000 setvmthreshold" (2 gigabytes) either alone or with -dBufferSpace didn't appear to make a difference.
Setting -sBandListStorage=memory resulted in a segmentation fault.
Setting -dMaxBitmap=2000000000 (2 gigabytes) significantly slowed down the process and apparently caused it to go haywire, writing hundreds of gigabytes of temporary files without any sign of stopping, prompting me to kill the process short.
Setting -dBandBufferSpace to half of -dBufferSpace didn't make a difference for smaller files, but actually slowed down the process rather significantly for larger files by 1.5-1.75x. In the Banding parameters section of the Ghostscript documentation, it's actually suggested not to use -dBandBufferSpace: "if you only want to allocate more memory for banding, to increase band size and improve performance, use the BufferSpace parameter, not BandBufferSpace."
I may be complete out of place here, but have you given a try to the Djvu file format ? It works like a charm for scanned documents in general (even if there are lots of pictures), and it gives much better compressed files: I get a factor of two lossless gain in size in general on B&W scientific articles.
We're currently using ps2pdf to convert EPS files to PDF. These EPS files contain both vector information (lines and text) and bitmap data.
However, by default ps2pdf converts the bitmap components of these images to JPG as they're embedded within the PDF, whereas for the type of graphics we have (data visualisation) it would be much more appropriate to use lossless compression. PDF supports PNG, so it should be possible to achieve what we're trying to do, but I'm having trouble finding a relevant option in the somewhat intimidating manual.
So the short question is: what is the correct way to write this?
ps2pdf -dPDFSETTINGS=UsePNGinsteadOfJPGcompression input.eps output.pdf
The answer is not -dUseFlateCompression, since that option refers to using Flate instead of LZW compression; both are lossless but LZW was covered by patents for a while. Since that's not a problem any more, the option is ignored.
Instead, the options called to achieve lossless encoding of bitmap data are: (all four of)
-dAutoFilterColorImages=false
-dAutoFilterGrayImages=false
-dColorImageFilter=/FlateEncode
-dGrayImageFilter=/FlateEncode
You might also want to do the same thing with MonoImageFilter as well, but I assume /CCITTFaxEncode does a reasonable job there so it's not too important.