代码之家  ›  专栏  ›  技术社区  ›  Miguel NoTeimporta

从创建PDF时丢失样式。带有Apache POI和Pdfbox的docx

  •  1
  • Miguel NoTeimporta  · 技术社区  · 6 年前

    该代码创建。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);
    

    关于丢失的图像,我没有任何线索,我尝试添加边距,在实例化文档和创建PDF选项之间添加以下代码:

        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 回复  |  直到 6 年前
        1
  •  2
  •   Miguel NoTeimporta    6 年前

    我设法找到了一个解决方案,但只适用于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的方法,我会发布它。