I need to create a pdf开发者_开发百科 file using Itext , here is the code
public static String generatePdfReport(){
try {
Document document = new Document();
PdfWriter.getInstance(document,new FileOutputStream("SimplePDFTableColspan.pdf"));
document.open();
PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell(new Paragraph("column span 2"));
cell.setColspan(2);
table.addCell(cell);
table.addCell("1");
table.addCell("2");
table.addCell("3");
table.addCell("4");
table.addCell("5");
table.addCell("6");
document.add(table);
document.close();
return document.toString();
} catch (Exception exe) {
exe.printStackTrace();
}
}
The problem the return type of the method is String but in Itext i am getting a document, so i am getting SAX exception:
Content is not allowed in prolog.
I'll assume that this is a static method with an empty paramter list. If that's the case, please correct your code.
Do you think it's wise to have an empty catch block? Your code will swallow any exception that's thrown and you won't be the wiser. Print the stack trace.
The method toString() of class Document seems to be inherited from class Object, and probably won't do what you intend (it certainly won't export the document as an XML String...).
Instead of a FileOutputStream, you could use a ByteArrayOutputStream, and then perform a string conversion on this data.
Document document = new Document();
ByteArrayOutputStream output = new ByteArrayOutputStream();
PdfWriter.getInstance(document, output);
document.open();
...
document.close();
....
return output.toString();
Regards,
Guillaume
精彩评论