How to write content into pdf use iText?

2019-05-06 23:51发布

问题:

Right now i use iText to generate a pdf automatically. And my problem is that when the content is really very large, i need to calculate the content's height and width, and then add new page... this is really very inconvinent.

so I wonder whether or not there is a method like: Document.add("a very very large article"); and after this , it will auto generate a pdf file ????

Thanks in advance !

回答1:

The following creates a 9 page pdf without having to calculate height and width.

import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class HelloWorld {
        public static void main(String[] args) {
                Document document = new Document();
                try {
                        PdfWriter.getInstance(document,
                                        new FileOutputStream("HelloWorld.pdf"));
                        document.open();
                        String text = "";
                        for (int i = 0; i < 10000; i++) {
                                text += "test";
                        }
                        document.add(new Paragraph(text));
                } catch (DocumentException e) {
                        System.err.println(e.getMessage());
                } catch (IOException ex) {
                        System.err.println(ex.getMessage());
                }
                document.close();
        }
}


回答2:

a new page will be generated automaticly, when the content of the current page is full.