Documents4j Remote Converter : Pdf file generated broken, can't open it

488 Views Asked by At

I've tried to convert a simple docx file to PDF through this code :

try {
InputStream in = testXdocReportDoc.class.getResourceAsStream("testXdocReportDocV2.docx");
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);

IContext context = report.createContext();
Project project = new Project("test1", "test2", "test3", "test4", "test5");
context.put("project", project);
File tempFile = new File(f.getAbsolutePath().replace("pdf", "docx"));
OutputStream out = new FileOutputStream(tempFile);
report.process(context, out);

out.flush();
out.close();
in.close();

IConverter converter2 = RemoteConverter.builder()
        .baseFolder(new File(HistorisationDevisManager.getAbsolutePathDevisPdf(devis)))
        .workerPool(20, 25, 2, TimeUnit.SECONDS)
        .requestTimeout(10, TimeUnit.SECONDS)
        .baseUri("http://localhost:8080")
        .build();

Future<Boolean> conversion = converter2
        .convert(tempFile).as(DocumentType.DOCX)
        .to(bo).as(DocumentType.PDF)
        .prioritizeWith(1000) // optional
        .schedule();
conversion.get();

try {
    OutputStream outputStream = new FileOutputStream(f);
    bo.writeTo(outputStream);
} catch (IOException e) {
    e.printStackTrace();
}
bo.close();
}  catch (Exception e) {
e.printStackTrace();
}
}

Everything seems to work, my docx is a simple file with "test" inside, but when I tried to open the generated PDF it's broken some how and I don't know why ...

1

There are 1 best solutions below

1
On

There are a bunch of loose ends in your code, I expect that it is related to these errors. You are opening but not closing all streams. Also, documents4j can handle file references, this should be preferred. Simply write your code like this:

converter2        
  .convert(testXdocReportDoc.class
    .getResourceAsStream("testXdocReportDocV2.docx")).as(DocumentType.DOCX)
  .to(new File("/write/to/this/location.pdf)).as(DocumentType.PDF)
  .schedule();