我正在尝试使用Java创建PDF文件。我所看到的是,我必须拥有iText库,所以我去了,就知道了。

这是我编写的代码,但是到处都是错误……这里出了点问题。

//com.lowagie.text.pdf.PdfWriter

public class document  {
    Document document = new Document (PageSize.A4, 50, 50, 50, 50);

    PdfWriter writer = PdfWriter.getInstance(document, \
    new FileOutputStream("C:\ITextTest.pdf"));
    document.open();

    document.add(new Paragraph("First page of the document."));
    //document.add(new Paragraph("Some more text on the \ first page with different color and font type.",
    //FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255, 150, 200))));

    document.close();
}

最佳答案

尝试这个:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.File;
import java.io.FileNotFoundException;

public class MyPDF {
    public static void main(String[] args) {

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        try {

            PdfWriter.getInstance(document, new FileOutputStream(new File(
                    "Test.pdf")));
            document.open();
            String content = "pdf data...";
            Paragraph paragraph = new Paragraph(content);
            document.add(paragraph);

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

09-27 14:11