简体   繁体   English

ITEXT中的Java pdf生成

[英]java pdf generation in ITEXT

I need to create a pdf file using Itext , here is the code 我需要使用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();
                         }
 }

The problem the return type of the method is String but in Itext i am getting a document, so i am getting SAX exception: 该方法的返回类型是String的问题,但是在Itext中,我正在获取文档,因此出现了SAX异常:

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...). Document类的toString()方法似乎是从Object类继承的,可能不会做您想要的事情(它当然不会将文档导出为XML String ...)。

Instead of a FileOutputStream, you could use a ByteArrayOutputStream, and then perform a string conversion on this data. 可以使用ByteArrayOutputStream代替FileOutputStream,然后对此数据执行字符串转换。

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

Regards, 问候,
Guillaume 纪尧姆

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

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