【问题标题】:Converting PDF to GRAYSCALE using PDFBox without images?使用没有图像的 PDFBox 将 PDF 转换为灰度?
【发布时间】:2019-03-11 06:05:05
【问题描述】:

我正在使用 Apache PDFBox,

我想在不使用图像方法的情况下将 RGB PDF 文件转换为另一个灰度文件,因为它会产生巨大的文件大小 -_- !!

这是我的步骤:

  1. 从 Adob​​e InDesign 导出 (A4) First.pdf,包含图像、文本、矢量对象。

  2. 我阅读了 First.pdf 文件。完成!

  3. 使用 LayerUtility,从 First.pdf 复制页面旋转它们并将它们放入新的 PDF 文件 (A4) Second.pdf。完成!

    • 首选此方法,因为我需要矢量对象来减小大小。
  4. 然后,我想将其保存为灰度 PDF 文件 (Second-grayscale.pdf)

这是我的代码(不是全部):

PDDocument documentFirst = PDDocument.load("First.pdf"));

// Second.pdf its empty always
PDDocument documentSecond = PDDocument.load("Second.pdf"));

for (int page = 0; page < documentSecond.getNumberOfPages(); page++) {
    // get current page from documentSecond
    PDPage tempPage = documentSecond.getPage(page);

    // create content contentStream
    PDPageContentStream contentStream = new PDPageContentStream(documentSecond, tempPage);

    // create layerUtility
    LayerUtility layerUtility = new LayerUtility(documentSecond);

    // importPageAsForm from documentFirst
    PDFormXObject form = layerUtility.importPageAsForm(documentFirst, page);

    // saveGraphicsState
    contentStream.saveGraphicsState();

    // rotate the page
    Matrix matrix;
    matrix.rotate(Math.toRadians(90));
    contentStream.transform(matrix);

    // draw the rotated page from documentFirst to documentSecond
    contentStream.drawForm(form);

    contentStream.close();
}

// save the new document
documentSecond.save("Second.pdf");

documentSecond.close();
documentFirst.close();

// now convert it to GRAYSCALE or do it in the Loop above!

好吧,我这周才开始使用 Apache Box,我已经关注了一些 例如,但大多数都老了,不能工作,直到现在我做了我所做的 需要,只需要灰度 :)!!

如果java中还有其他使用开源库的解决方案 或免费工具。 (我发现了 Ghost Script 和 Python)

我读了这个例子,但我不明白它有一个功能被弃用了!:

https://github.com/lencinhaus/pervads/blob/master/libs/pdfbox/src/java/org/apache/pdfbox/ConvertColorspace.java

关于 PDF 规范和更改色彩空间...

【问题讨论】:

  • 该示例仅适用于简单文档。但是一个完整的解决方案非常重要。
  • PDFBox可以做灰度转换吗?
  • 不是“开箱即用”。
  • 据我所知,没有现成的成熟 pdfbox 转换例程,您引用的示例仅涵盖非常简单的情况。另一方面,pdfbox 为任意 pdf 操作提供了一个框架;因此,您可以基于 pdfbox 实现自己的转换。所以... “PDFBox 可以进行灰度转换吗?” - 是的,但可能不是开箱即用的。加上你不分享有问题的 pdf(或 pdf 的代表性示例),我无法判断你找到的示例是否已经足够。

标签: java pdf pdf-generation pdfbox


【解决方案1】:

据我所知,您提到您会对基于 Ghostscript 的解决方案感兴趣。 如果您能够从命令行调用 GS,则可以使用此命令行进行颜色到灰度的转换

gs -sDEVICE=pdfwrite -sProcessColorModel=DeviceGray -sColorConversionStrategy=Gray -dOverrideICC -o out.pdf -f input.pdf

我的回答来自How to convert a PDF to grayscale from command line avoiding to be rasterized?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-13
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    相关资源
    最近更新 更多