首页 文章

使用Apache POI和Pdfbox从.docx创建PDF时丢失样式

提问于
浏览
0

代码创建.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 .

1 回答

  • 0

    我设法找到了一个解决方案,但只适用于Windows(可能很容易转换为在Linux中使用,但我没有看起来像打印的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的方法,我会发布它 .

相关问题