java 生成表格并添加水印
为了生成表格并添加水印,我们可以使用Apache POI和iText库。下面是一个示例代码:
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TableWithWatermark {
public static void main(String[] args) {
String fileName = "table_with_watermark.pdf";
String watermark = "Confidential";
int numRows = 10;
int numCols = 5;
// Create a new workbook and sheet
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// Generate random data and fill the sheet
for (int i = 0; i < numRows; i++) {
Row row = sheet.createRow(i);
for (int j = 0; j < numCols; j++) {
Cell cell = row.createCell(j);
cell.setCellValue(Math.random() * 100);
}
}
try {
// Create a new PDF document
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
document.open();
PdfContentByte cb = writer.getDirectContent();
// Add the watermark to the PDF document
Phrase watermarkPhrase = new Phrase(watermark);
float fontSize = 60;
float x = (document.getPageSize().getWidth() - watermarkPhrase.getWidthPoint()) / 2;
float y = (document.getPageSize().getHeight() - watermarkPhrase.getHeightPoint()) / 2;
cb.beginText();
cb.setFontAndSize(watermarkPhrase.getFont(), fontSize);
cb.showTextAligned(Element.ALIGN_CENTER, watermark, x, y, 45);
cb.endText();
// Create a new table and add it to the PDF document
PdfPTable table = new PdfPTable(numCols);
for (int i = 0; i < numRows; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < numCols; j++) {
Cell cell = row.getCell(j);
PdfPCell pdfCell = new PdfPCell(new Phrase(cell.toString()));
table.addCell(pdfCell);
}
}
document.add(table);
document.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个示例中,我们首先使用Apache POI生成一个Excel表格,然后使用iText将其写入PDF文件。我们还添加了一个水印,该水印位于PDF页面的中心。最后,我们将Excel表格中的数据添加到PDF表格中
原文地址: https://www.cveoy.top/t/topic/cvSz 著作权归作者所有。请勿转载和采集!