繁体   English   中英

ITEXT中的Java pdf生成

[英]java pdf generation in 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异常:

序言中不能有内容。

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

您认为拥有一个空的捕获块是否明智? 您的代码将吞下所有抛出的异常,您将不再明智。 打印堆栈跟踪。

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

问候,
纪尧姆

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM