【问题标题】:Losing styles when create a PDF from a .docx with Apache POI and Pdfbox使用 Apache POI 和 Pdfbox 从 .docx 创建 PDF 时丢失样式
【发布时间】:2018-05-08 06:26:43
【问题描述】:

代码创建一个 .docx,然后从中创建一个 PDF。打开时,边距和样式与 .docx 不匹配,但主要问题是文本已移动,并且丢失了一些图像。创建 PDF 的代码:

    InputStream doc = new FileInputStream(new File(sourcePath + name));
    XWPFDocument document = new XWPFDocument(doc);

    PdfOptions options = PdfOptions.getDefault();
    OutputStream out = new FileOutputStream(new File(destinationPath + name.replace("." + MimeUtil2.getExtension(name), "") + ".pdf"));
    PdfConverter.getInstance().convert(document, out, options);

关于丢失的图像我不知道,我尝试添加边距,在实例化文档和创建 PdfOptions 之间添加以下代码:

    CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
    CTPageMar pageMar = sectPr.addNewPgMar();
    pageMar.setLeft(BigInteger.valueOf(720L));
    pageMar.setTop(BigInteger.valueOf(1440L));
    pageMar.setRight(BigInteger.valueOf(720L));
    pageMar.setBottom(BigInteger.valueOf(1440L));

但不工作。

我找到了一种修改边距的方法:在创建 .docx 时添加上面相同的代码,它似乎可以工作。但这并不能解决丢失图像和移动文本的问题。此外,它使代码更丑陋并且感觉不对,因为样式是在之后正确添加的(在 .docx 的编写中)。

如何保留 .docx 中的样式或添加它们以使 PDF 最接近 .docx?

Java 1.8、Apache POI 3.15 和 Pdfbox 2.0.9。

【问题讨论】:

  • 您的问题与 iText 无关。标记已删除。
  • 我不明白 PDFBox 是怎么回事,那里没有 PDFBox 代码。 PdfConverter 来自 POI(或者它在后台使用 PDFBox?)。
  • 你说得对,我用的是 PDFBox,但后来打印第一个 PDF 以将多个 PDF 合并为一个。

标签: java pdf apache-poi


【解决方案1】:

我设法找到了一个解决方案,但仅适用于 Windows(可能很容易转换为在 Linux 中使用,但我没有研究它)。我的问题是 .docx 看起来与打印的 PDF 不完全相同。我使用OfficeToPDF 并用java 调用它。命令行是这样的:

[path-to-officetopdf]/officetopdf.exe [source]\myFile.docx [destination]\myNewPDF.pdf

对于任何可能关心的人,这是您使用 java 执行 shell 命令的方式:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public static String executeShellCommand(String command) {
        StringBuffer output = new StringBuffer();

    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";           
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

}

我希望这可以帮助某人,如果我找到了用 Linux 制作它的方法,我会发布它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2011-08-28
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多