使用 JAVA (Netbeans) 创建包含图像和多页的 PDF

Creating PDF using JAVA (Netbeans) with images and multi pages

我正在开发具有以下要求的 Java 程序:

如何使用 iText 实现这样的解决方案?

您可以使用 XSL-FO。一个基本的例子 here。在此之后,您可以为您的 PDF 搜索和添加其他选项。

  • The application will take 5 input fields and 3 images (browse and "attach" to the Java application).
  • Once the "form" is completed it will be submitted using a button called "submit".

前两个要求不清楚;它们是在 Java GUI(AWT?Swing?FX?)、一些独立的网络 UI(Plain HTML?Vaadin?)或在一些派生UI(Portlet?...)?

但是由于问题标题“使用 JAVA (Netbeans) 使用图像和多页创建 PDF”关注于 PDF 创建,让我们看一下第三个和第四个要求.

  • Once submitted the JAVA application will create a PDF file with the 5 inputed text and the 3 attached images.
  • I should be able to control which goes to which page number.

假设您已经在变量中输入了这些内容

String text1, text2, text3, text4, text5;
byte[] image1, image2, image3;

框架

使用 iText,您现在可以像这样创建文档:

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;

...

// where you want to create the PDF;
// use a FileOutputStream for creating the PDF in the file system
// use a ByteArrayOutputStream for creating the PDF in a byte[] in memory
OutputStream output = ...; 
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();

// Add content for the first page(s)
...
// Start e new page
document.newPage();
// Add content for the next page(s)
...
// Start a new page
document.newPage();
// etc etc

document.close();

添加文本

您可以使用

Add content for the ... page(s) 部分之一中添加文本
import com.itextpdf.text.Paragraph;

...

document.add(new Paragraph(text1));

添加图像

您可以使用

Add content for the ... page(s) 部分之一中添加图片
import com.itextpdf.text.Image;

...

document.add(Image.getInstance(image1));

在给定位置添加

如上所述添加文本或图像将布局细节留给 iText,iText 从上到下填充页面,除了一些边距。

如果你想自己控制内容的定位(这也意味着你必须注意内容部分不重叠或绘制在页面区域之外),你可以这样做:

import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.Phrase;

...

PdfContentByte canvas = writer.getDirectContent();
Phrase phrase = new Phrase(text2);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase, 200, 572, 0);

Image img = Image.getInstance(image2);
img.setAbsolutePosition(200, 200);
canvas.addImage(img);

还有更多操作内容的选项,例如选择字体、选择文本大小、缩放图像、旋转内容...,只需看看 iText in Action - 第二版 一书中的 iText samples。 =20=]