jar 包 : itext-asian-5.2.0.jar itextpdf-5.5.5.jar itext-1.4.6.jar
Java 用 iText5 操作 PDF itext-asian-5.2.0.jar itextpdf-5.5.5.jar itext-1.4.6.jar
Descripción
Crea un nuevo objeto de documento
- Documento documento = nuevo Documento (); // El tamaño de página predeterminado es A4
- Documento documento = nuevo documento (PageSize.A4); // Especifique el tamaño de página como A4
- Document document = new Document (PageSize.A4,50,50,30,20); // Especifique el tamaño de la página como A4 y personalice los márgenes
Objeto PdfWriter para operaciones de escritura en disco
PdfWriter.getInstance (documento, nuevo FileOutputStream (filePath));
Abrir documento
document.open ();
Agregar contenido al documento
document.add ();
Cerrar documento
document.close ();
Párrafo
Párrafo pt = nuevo párrafo (nombre, fuente); // Establecer estilo de fuente
pt.setAlignment (1); // Establece el texto en el centro 0 a la izquierda 1, centro 2 y derecha
pt.setIndentationLeft (12); // Sangría izquierda
pt.setIndentationRight (12); // Sangría derecha
pt.setFirstLineIndent (24); // Sangría de la primera línea
paragraph.setLeading (20f); // Interlineado
paragraph.setSpacingBefore (5f); // Establecer el espacio en blanco en el párrafo
paragraph.setSpacingAfter (10f); // Establece el espacio debajo del párrafo
Mesa
Table table = new Table (4); // El parámetro entre paréntesis indica la columna
int width [] = {10,40,40}; // Establece la relación de ancho de cada columna
table.setWidths (ancho);
table.setWidth (60); // Contabilización de la proporción de ancho de página
table.setAlignment (Element.ALIGN_LEFT); // 居 左
table.setAutoFillEmptyCells (true); // Autocompletar
table.setBorderWidth ((float) 0.1); // El ancho de la línea del borde de la tabla
table.setPadding (1); // Margen: el margen entre el borde de la celda y el contenido de la celda
table.setSpacing (0); // Espaciado: la distancia entre la celda y la celda
table.addCell (new Paragraph ("nombre"), "celda")); // Agregar contenido de celda
table.endHeaders (); // Cada página mostrará el encabezado
Ejemplo
Genera un pdf con solo el título
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
public class PdfJava
{
public void pdfTest(String filePath) throws Exception
{
Document document = new Document(PageSize.A4, 36, 36, 36, 36);
PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
//中文字体,解决中文不能显示问题
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
Font cusTitleFont = new Font(bfChinese);
cusTitleFont.setSize(16);
Font cusFont = new Font(bfChinese);
cusFont.setSize(9);
//添加标题开始
Font redFont = new Font(bfChinese);
redFont.setColor(BaseColor.RED);//设置颜色
redFont.setSize(20);//设置字体大小
Paragraph chapterTitle = new Paragraph("java生成pdf文件", redFont);//设置内容
chapterTitle.setAlignment(1);
Chapter chapter1 = new Chapter(chapterTitle, 1);
chapter1.setNumberDepth(0);
document.add(chapter1);
//添加标题结束
//关闭文档
document.close();
}
/**
* @param args
*/
public static void main(String[] args)
{
try
{
String filePath="d:\\test1.pdf";
new PdfJava().pdfTest(filePath);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Los archivos son los siguientes:
Generar contenido de tabla
import java.io.FileOutputStream;
import java.util.List;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPRow;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class PdfJava
{
public void pdfTest(String filePath) throws Exception
{
Document document = new Document(PageSize.A4, 36, 36, 36, 36);
PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
//中文字体,解决中文不能显示问题
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
Font cusTitleFont = new Font(bfChinese);
cusTitleFont.setSize(16);
Font cusFont = new Font(bfChinese);
cusFont.setSize(9);
//添加标题开始
Font redFont = new Font(bfChinese);
redFont.setColor(BaseColor.RED);//设置颜色
redFont.setSize(20);//设置字体大小
Paragraph chapterTitle = new Paragraph("java生成pdf文件", redFont);//设置内容
chapterTitle.setAlignment(1);
Chapter chapter1 = new Chapter(chapterTitle, 1);
chapter1.setNumberDepth(0);
document.add(chapter1);
//添加标题结束
//添加一个内容段落
document.add(new Paragraph("表格信息", cusTitleFont));
// 表格.
PdfPTable table = new PdfPTable(6);
table.setWidthPercentage(100); // 宽度100%填充
table.setSpacingBefore(10f); // 前间距
table.setSpacingAfter(10f); // 后间距
List<PdfPRow> listRow = table.getRows();
//设置列宽
float[] columnWidths = { 2f, 2f, 2f ,2f, 2f, 2f};
table.setWidths(columnWidths);
//行
PdfPCell cells1[] = new PdfPCell[6];
PdfPRow row1 = new PdfPRow(cells1);
//单元格
cells1[0] = new PdfPCell(new Paragraph("第一行第1列:", cusFont));//单元格内容
cells1[0].setHorizontalAlignment(Element.ALIGN_RIGHT);//水平居右
cells1[1] = new PdfPCell(new Paragraph("第一行第1列值", cusFont));
cells1[1].setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
cells1[2] = new PdfPCell(new Paragraph("第一行第2列:", cusFont));//单元格内容
cells1[2].setHorizontalAlignment(Element.ALIGN_RIGHT);//水平居右
cells1[3] = new PdfPCell(new Paragraph("第一行第2列值", cusFont));
cells1[3].setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
cells1[4] = new PdfPCell(new Paragraph("第一行第3列:", cusFont));//单元格内容
cells1[4].setHorizontalAlignment(Element.ALIGN_RIGHT);//水平居右
cells1[5] = new PdfPCell(new Paragraph("第一行第3列值", cusFont));
cells1[5].setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
//把第一行添加到集合
listRow.add(row1);
//行
PdfPCell cells2[] = new PdfPCell[6];
PdfPRow row2 = new PdfPRow(cells2);
//单元格
cells2[0] = new PdfPCell(new Paragraph("第二行第1列:", cusFont));//单元格内容
cells2[0].setHorizontalAlignment(Element.ALIGN_RIGHT);//水平居右
cells2[1] = new PdfPCell(new Paragraph("第二行第1列值", cusFont));
cells2[1].setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
cells2[2] = new PdfPCell(new Paragraph("第二行第2列:", cusFont));//单元格内容
cells2[2].setHorizontalAlignment(Element.ALIGN_RIGHT);//水平居右
cells2[3] = new PdfPCell(new Paragraph("第二行第2列值", cusFont));
cells2[3].setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
cells2[4] = new PdfPCell(new Paragraph("第二行第3列:", cusFont));//单元格内容
cells2[4].setHorizontalAlignment(Element.ALIGN_RIGHT);//水平居右
cells2[5] = new PdfPCell(new Paragraph("第二行第3列值", cusFont));
cells2[5].setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
//把第二行添加到集合
listRow.add(row2);
//把表格添加到文件中
document.add(table);
//关闭文档
document.close();
}
/**
* @param args
*/
public static void main(String[] args)
{
try
{
String filePath="d:\\test1.pdf";
new PdfJava().pdfTest(filePath);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Los archivos son los siguientes:
Agregar sello oficial (imagen)
Image image1 = Image.getInstance("d:\\gongzhang.jpg");
//设置图片位置的x轴和y轴
image1.setAbsolutePosition(100, 500);//注意是从文档的坐下角往右、往上计算的
//设置图片的宽度和高度
image1.scaleAbsolute(100, 100);
//将图片1添加到pdf文件中
document.add(image1);
Agregar información del autor
//Anchor对象: internal and external links
Paragraph country = new Paragraph();
Anchor dest = new Anchor("china", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
dest.setName("CN");
dest.setReference("http://www.china.com");//external
country.add(dest);
country.add(String.format(": %d sites", 10000));
document.add(country);
Únase para saltar a la ubicación especificada (haga clic para saltar)
document.newPage();
Anchor toUS = new Anchor("Go to first page.", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
toUS.setReference("#CN");//internal
document.add(toUS);
HTML a PDF
Java usa iText5 para manipular el código PDF y las descargas jar relacionadas