以"lossless"的方式将jpg图片存入pdf文件

Storing jpg images into a pdf file in a "lossless" way

给定一个包含多个 jpg 文件(照片)的目录,我会 喜欢创建一个 pdf 文件,每页一张照片。 但是,我希望将照片原封不动地存储在 pdf 文件中;即,我想避免解码和重新编码。 所以理想情况下,我希望能够从 pdf 文件中提取原始 jpg 文件(可能减去元数据),例如使用 linux 命令行太像 pdfimages.

我目前的想法:

您可以使用以下依赖于 HexaPDF(注意:我是 HexaPDF 的作者)的小脚本来执行此操作。

注意:确保您已安装 Ruby 2.4,然后 运行 gem install hexapdf 安装 hexapdf。

这是脚本:

require 'hexapdf'

doc = HexaPDF::Document.new

ARGV.each do |image_file|
  image = doc.images.add(image_file)
  page = doc.pages.add
  iw = image.info.width.to_f
  ih = image.info.height.to_f                                                                                                                             
  pw = page.box(:media).width.to_f
  ph = page.box(:media).height.to_f
  rw, rh = pw / iw, ph / ih
  ratio = [rw, rh].min
  iw, ih = iw * ratio, ih * ratio
  x, y = (pw - iw) / 2, (ph - ih) / 2
  page.canvas.image(image, at: [x, y], width: iw, height: ih)
end

doc.write('images.pdf')

只需在命令行中提供图像作为参数,输出文件将被命名为images.pdf。大多数代码处理图像的居中和缩放以很好地适合页面。

img2pdf (PyPI page):

Losslessly convert raster images to PDF without re-encoding PNG, JPEG, and JPEG2000 images. This leads to a lossless conversion of PNG, JPEG and JPEG2000 images with the only added file size coming from the PDF container itself. Other raster graphics formats are losslessly stored using the same encoding that PNG uses. Since PDF does not support images with transparency and since img2pdf aims to never be lossy, input images with an alpha channel are not supported.

pdfimages -all 正好相反。)

另一种以“无损”方式将 jpg 图像存储到 pdf 文件的可能性由 PoDoFo 提供:

podofoimg2pdf 能够通过将 jpg 文件嵌入 pdf 容器来执行从 JPEG 到 PDF 的无损转换。

podofoimg2pdf
Usage: podofoimg2pdf [output.pdf] [-useimgsize] [image1 image2 image3 ...]

Options:
 -useimgsize    Use the imagesize as page size, instead of A4

根据您希望对文件执行的操作,在 windows 上,如果图像更简单 jpeg/gif/tif/png 您可以存储在 cbz、zip、文件夹或压缩文件夹中并使用 SumatraPDF 查看它具有 SaveAs PDF 选项,因此所有操作都通过一个 exe 完成。

对于可查看但不能作为 PDF 输入(例如 webp 或 heic)的文件,它将失败,因此请在查看器中检查文件扩展名之前的内容。

它在几乎所有情况下都应该是无损的,但是您应该使用 pdfimage -all 进行往返以在输入和输出之间进行文件比较以检查是否需要转换任何字节。