简体   繁体   中英

Converting JPG image to PDF without resizing image with ghostscript or itext

I'm trying to merge images in JPG format with standard PDF documents, while keeping images in the same size. Earlier I was using ImageMagick's convert , but it results in huge quality drop since it converts everything into images, so I'm switching to ghostscript (or eventually itextpdf).

I found this code which inserts scaled image into A4 page:

gs \
 -sDEVICE=pdfwrite \
 -o foo.pdf \
  /usr/local/share/ghostscript/8.71/lib/viewjpeg.ps \
 -c \(my.jpg\) viewJPEG

PdfWriter from itextpdf in this way or that way could be alternative but it also adds an image into a page.

After inspecting ImageMagick's behavioral, I found out command it was using which I think is closest to my solution, but it doesn't seem to work when I'm trying to modify or use it. How should I modify it?

gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=pngalpha -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72  -sOutputFile=out_gs.pdf fox_big.jpg

The answer to your question can be found on the official iText web site: How to add multiple images into a single PDF?

In the MultipleImages example, we take a selection of images, and we convert them to a PDF: multiple_images.pdf

The page size is set to match the size of the image:

For the first image:

Image img = Image.getInstance(IMAGES[0]);
Document document = new Document(img);

As you can see, we pass the img to the Document constructor. This works, because Image extends the Rectangle class.

For the subsequent images, we change the page size:

document.setPageSize(img);

Note that we also need to set the absolute position:

img.setAbsolutePosition(0, 0);

Please go to the official web site when you want to find info and examples on iText. I've spent many months writing all that content and putting it on the web site. It's frustrating when I see that people don't take advantage of all that work. (It feels like I wasted my time.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM