文章18 | 阅读 10900 | 点赞0
本章的例子,请参考我翻译的博文:itext7学习笔记——第3章,里面有详细的解释,有什么不懂得也可以评论或者私信我!
页面划分成三栏,然后添加文本和图片,代码如下:
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.ColumnDocumentRenderer;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
/** * Simple column renderer example. */
public class C03E01_NewYorkTimes {
public static final String DEST = "results/chapter03/new_york_times.pdf";
public static final String APPLE_IMG = "src/main/resources/img/ny_times_apple.jpg";
public static final String APPLE_TXT = "src/main/resources/data/ny_times_apple.txt";
public static final String FACEBOOK_IMG = "src/main/resources/img/ny_times_fb.jpg";
public static final String FACEBOOK_TXT = "src/main/resources/data/ny_times_fb.txt";
public static final String INST_IMG = "src/main/resources/img/ny_times_inst.jpg";
public static final String INST_TXT = "src/main/resources/data/ny_times_inst.txt";
static PdfFont timesNewRoman = null;
static PdfFont timesNewRomanBold = null;
public static void main(String[] args) throws Exception {
timesNewRoman = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
timesNewRomanBold = PdfFontFactory.createFont(FontConstants.TIMES_BOLD);
File file = new File(DEST);
file.getParentFile().mkdirs();
new C03E01_NewYorkTimes().createPdf(DEST);
}
protected void createPdf(String dest) throws Exception {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PageSize ps = PageSize.A5;
// Initialize document
Document document = new Document(pdf, ps);
//Set column parameters
float offSet = 36;
float columnWidth = (ps.getWidth() - offSet * 2 + 10) / 3;
float columnHeight = ps.getHeight() - offSet * 2;
//Define column areas
Rectangle[] columns = {new Rectangle(offSet - 5, offSet, columnWidth, columnHeight),
new Rectangle(offSet + columnWidth, offSet, columnWidth, columnHeight),
new Rectangle(offSet + columnWidth * 2 + 5, offSet, columnWidth, columnHeight)};
document.setRenderer(new ColumnDocumentRenderer(document, columns));
Image apple = new Image(ImageDataFactory.create(APPLE_IMG)).setWidth(columnWidth);
String articleApple = new String(Files.readAllBytes(Paths.get(APPLE_TXT)), StandardCharsets.UTF_8);
C03E01_NewYorkTimes.addArticle(document, "Apple Encryption Engineers, if Ordered to Unlock iPhone, Might Resist", "By JOHN MARKOFF MARCH 18, 2016", apple, articleApple);
Image facebook = new Image(ImageDataFactory.create(FACEBOOK_IMG)).setWidth(columnWidth);
String articleFB = new String(Files.readAllBytes(Paths.get(FACEBOOK_TXT)), StandardCharsets.UTF_8);
C03E01_NewYorkTimes.addArticle(document, "With \"Smog Jog\" Through Beijing, Zuckerberg Stirs Debate on Air Pollution", "By PAUL MOZUR MARCH 18, 2016", facebook, articleFB);
Image inst = new Image(ImageDataFactory.create(INST_IMG)).setWidth(columnWidth);
String articleInstagram = new String(Files.readAllBytes(Paths.get(INST_TXT)), StandardCharsets.UTF_8);
C03E01_NewYorkTimes.addArticle(document, "Instagram May Change Your Feed, Personalizing It With an Algorithm","By MIKE ISAAC MARCH 15, 2016", inst, articleInstagram);
document.close();
}
public static void addArticle(Document doc, String title, String author, Image img, String text) throws IOException {
Paragraph p1 = new Paragraph(title)
.setFont(timesNewRomanBold)
.setFontSize(14);
doc.add(p1);
doc.add(img);
Paragraph p2 = new Paragraph()
.setFont(timesNewRoman)
.setFontSize(7)
.setFontColor(Color.GRAY)
.add(author);
doc.add(p2);
Paragraph p3 = new Paragraph()
.setFont(timesNewRoman)
.setFontSize(10)
.add(text);
doc.add(p3);
}
}
绘制一个表格,第一栏为圆角单元格,每一列的背景颜色不同,根据列号而定,代码如下:
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.color.DeviceCmyk;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.border.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
import java.io.*;
import java.util.StringTokenizer;
/** * Simple table renderer example. */
public class C03E02_PremierLeague {
public static final String DATA = "src/main/resources/data/premier_league.csv";
public static final String DEST = "results/chapter03/premier_league.pdf";
Color greenColor = new DeviceCmyk(0.78f, 0, 0.81f, 0.21f);
Color yellowColor = new DeviceCmyk(0, 0, 0.76f, 0.01f);
Color redColor = new DeviceCmyk(0, 0.76f, 0.86f, 0.01f);
Color blueColor = new DeviceCmyk(0.28f, 0.11f, 0, 0);
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new C03E02_PremierLeague().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PageSize ps = new PageSize(842, 680);
// Initialize document
Document document = new Document(pdf, ps);
PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA);
PdfFont bold = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
Table table = new Table(new float[]{1.5f, 7, 2, 2, 2, 2, 3, 4, 4, 2});
table.setWidthPercent(100)
.setTextAlignment(TextAlignment.CENTER)
.setHorizontalAlignment(HorizontalAlignment.CENTER);
BufferedReader br = new BufferedReader(new FileReader(DATA));
String line = br.readLine();
process(table, line, bold, true);
while ((line = br.readLine()) != null) {
process(table, line, font, false);
}
br.close();
document.add(table);
//Close document
document.close();
}
public void process(Table table, String line, PdfFont font, boolean isHeader) {
StringTokenizer tokenizer = new StringTokenizer(line, ";");
int columnNumber = 0;
while (tokenizer.hasMoreTokens()) {
if (isHeader) {
Cell cell = new Cell().add(new Paragraph(tokenizer.nextToken()));
cell.setNextRenderer(new RoundedCornersCellRenderer(cell));
cell.setPadding(5).setBorder(null);
table.addHeaderCell(cell);
} else {
columnNumber++;
Cell cell = new Cell().add(new Paragraph(tokenizer.nextToken()));
cell.setFont(font).setBorder(new SolidBorder(Color.BLACK, 0.5f));
switch (columnNumber) {
case 4:
cell.setBackgroundColor(greenColor);
break;
case 5:
cell.setBackgroundColor(yellowColor);
break;
case 6:
cell.setBackgroundColor(redColor);
break;
default:
cell.setBackgroundColor(blueColor);
break;
}
table.addCell(cell);
}
}
}
private class RoundedCornersCellRenderer extends CellRenderer {
public RoundedCornersCellRenderer(Cell modelElement) {
super(modelElement);
}
@Override
public void drawBorder(DrawContext drawContext) {
Rectangle rectangle = getOccupiedAreaBBox();
float llx = rectangle.getX() + 1;
float lly = rectangle.getY() + 1;
float urx = rectangle.getX() + getOccupiedAreaBBox().getWidth() - 1;
float ury = rectangle.getY() + getOccupiedAreaBBox().getHeight() - 1;
PdfCanvas canvas = drawContext.getCanvas();
float r = 4;
float b = 0.4477f;
canvas.moveTo(llx, lly).lineTo(urx, lly).lineTo(urx, ury - r)
.curveTo(urx, ury - r * b, urx - r * b, ury, urx - r, ury)
.lineTo(llx + r, ury)
.curveTo(llx + r * b, ury, llx, ury - r * b, llx, ury - r)
.lineTo(llx, lly).stroke();
super.drawBorder(drawContext);
}
}
绘制一个表格,奇偶页背景颜色不同,添加页眉、页脚和水印,代码如下:
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.color.DeviceCmyk;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.border.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.Property;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.layout.property.VerticalAlignment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
/** * Simple event handler example. */
public class C03E03_UFO {
public static final String DATA = "src/main/resources/data/ufo.csv";
public static final String DEST = "results/chapter03/ufo.pdf";
static PdfFont helvetica = null;
static PdfFont helveticaBold = null;
public static void main(String[] args) throws Exception {
helvetica = PdfFontFactory.createFont(FontConstants.HELVETICA);
helveticaBold = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
File file = new File(DEST);
file.getParentFile().mkdirs();
new C03E03_UFO().createPdf(DEST);
}
protected void createPdf(String dest) throws Exception {
//Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new MyEventHandler());
// Initialize document
Document document = new Document(pdf);
Paragraph p = new Paragraph("List of reported UFO sightings in 20th century")
.setTextAlignment(TextAlignment.CENTER).setFont(helveticaBold).setFontSize(14);
document.add(p);
Table table = new Table(UnitValue.createPercentArray(new float[]{3, 5, 7, 4}));
BufferedReader br = new BufferedReader(new FileReader(DATA));
String line = br.readLine();
process(table, line, helveticaBold, true);
while ((line = br.readLine()) != null) {
process(table, line, helvetica, false);
}
br.close();
document.add(table);
document.close();
}
public void process(Table table, String line, PdfFont font, boolean isHeader) {
StringTokenizer tokenizer = new StringTokenizer(line, ";");
while (tokenizer.hasMoreTokens()) {
if (isHeader) {
table.addHeaderCell(new Cell().add(new Paragraph(tokenizer.nextToken()).setFont(font)).setFontSize(9).setBorder(new SolidBorder(Color.BLACK, 0.5f)));
} else {
table.addCell(new Cell().add(new Paragraph(tokenizer.nextToken()).setFont(font)).setFontSize(9).setBorder(new SolidBorder(Color.BLACK, 0.5f)));
}
}
}
protected class MyEventHandler implements IEventHandler {
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdfDoc = docEvent.getDocument();
PdfPage page = docEvent.getPage();
int pageNumber = pdfDoc.getPageNumber(page);
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
//Set background
Color limeColor = new DeviceCmyk(0.208f, 0, 0.584f, 0);
Color blueColor = new DeviceCmyk(0.445f, 0.0546f, 0, 0.0667f);
pdfCanvas.saveState()
.setFillColor(pageNumber % 2 == 1 ? limeColor : blueColor)
.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight())
.fill().restoreState();
//Add header and footer
pdfCanvas.beginText()
.setFontAndSize(helvetica, 9)
.moveText(pageSize.getWidth() / 2 - 60, pageSize.getTop() - 20)
.showText("THE TRUTH IS OUT THERE")
.moveText(60, -pageSize.getTop() + 30)
.showText(String.valueOf(pageNumber))
.endText();
//Add watermark
Canvas canvas = new Canvas(pdfCanvas, pdfDoc, page.getPageSize());
canvas.setFontColor(Color.WHITE);
canvas.setProperty(Property.FONT_SIZE, 60);
canvas.setProperty(Property.FONT, helveticaBold);
canvas.showTextAligned(new Paragraph("CONFIDENTIAL"), 298, 421, pdfDoc.getPageNumber(page),
TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
pdfCanvas.release();
}
}
}
本章代码可在如下地址下载(IDEA工程):iText7——第三章源代码工程
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/u012397189/article/details/77541052
内容来源于网络,如有侵权,请联系作者删除!