ITEXT中的java pdf生成

时间:2011-02-22 13:21:46

标签: java pdf itext

我需要使用Itext创建一个pdf文件,这里是代码

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();
                         }
 }

方法的返回类型是String的问题但在Itext中我得到一个文档,所以我得到SAX异常:

  

prolog中不允许使用内容。

2 个答案:

答案 0 :(得分:0)

我假设这是一个带有空参数列表的静态方法。如果是这种情况,请更正您的代码。

你觉得拥有空挡块是明智的吗?您的代码将吞下任何抛出的异常,您将不会更聪明。打印堆栈跟踪。

答案 1 :(得分:-1)

类Document的toString()方法似乎是从Object类继承的,可能不会按照你想要的方式执行(它肯定不会将文档导出为XML String ...)。

您可以使用ByteArrayOutputStream代替FileOutputStream,然后对此数据执行字符串转换。

Document document = new Document();
ByteArrayOutputStream output = new ByteArrayOutputStream();
PdfWriter.getInstance(document, output);
document.open();
...
document.close();
....
return output.toString();

的问候,
纪尧姆