JAVA-29281 Create new module Text Processing Libraries Modules (#15479)

This commit is contained in:
anuragkumawat
2023-12-31 08:37:40 -08:00
committed by GitHub
parent 1768eee09f
commit 76bde3ff46
78 changed files with 208 additions and 189 deletions
@@ -0,0 +1,242 @@
package com.baeldung.exceltopdf;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ExcelToPDFConverter {
private static final Logger logger = LogManager.getLogger(ExcelToPDFConverter.class);
public static XSSFWorkbook readExcelFile(String excelFilePath) throws IOException {
FileInputStream inputStream = new FileInputStream(excelFilePath);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
inputStream.close();
return workbook;
}
private static Document createPDFDocument(String pdfFilePath) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath));
document.open();
return document;
}
public static void convertExcelToPDF(String excelFilePath, String pdfFilePath) throws IOException, DocumentException {
XSSFWorkbook workbook = readExcelFile(excelFilePath);
Document document = createPDFDocument(pdfFilePath);
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
XSSFSheet worksheet = workbook.getSheetAt(i);
// Add header with sheet name as title
Paragraph title = new Paragraph(worksheet.getSheetName(), new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD));
title.setSpacingAfter(20f);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
createAndAddTable(worksheet, document);
// Add a new page for each sheet (except the last one)
if (i < workbook.getNumberOfSheets() - 1) {
document.newPage();
}
}
document.close();
workbook.close();
}
private static void createAndAddTable(XSSFSheet worksheet, Document document) throws DocumentException, IOException {
PdfPTable table = new PdfPTable(worksheet.getRow(0)
.getPhysicalNumberOfCells());
table.setWidthPercentage(100);
addTableHeader(worksheet, table);
addTableData(worksheet, table);
document.add(table);
}
private static void addTableHeader(XSSFSheet worksheet, PdfPTable table) throws DocumentException, IOException {
Row headerRow = worksheet.getRow(0);
for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
Cell cell = headerRow.getCell(i);
String headerText = getCellText(cell);
PdfPCell headerCell = new PdfPCell(new Phrase(headerText, getCellStyle(cell)));
setBackgroundColor(cell, headerCell);
setCellAlignment(cell, headerCell);
table.addCell(headerCell);
}
}
public static String getCellText(Cell cell) {
String cellValue;
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(BigDecimal.valueOf(cell.getNumericCellValue()));
break;
case BLANK:
default:
cellValue = "";
break;
}
return cellValue;
}
private static void addTableData(XSSFSheet worksheet, PdfPTable table) throws DocumentException, IOException {
Iterator<Row> rowIterator = worksheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
if (row.getRowNum() == 0) {
continue;
}
for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
Cell cell = row.getCell(i);
String cellValue = getCellText(cell);
PdfPCell cellPdf = new PdfPCell(new Phrase(cellValue, getCellStyle(cell)));
setBackgroundColor(cell, cellPdf);
setCellAlignment(cell, cellPdf);
table.addCell(cellPdf);
}
}
}
private static void setBackgroundColor(Cell cell, PdfPCell cellPdf) {
// Set background color
short bgColorIndex = cell.getCellStyle()
.getFillForegroundColor();
if (bgColorIndex != IndexedColors.AUTOMATIC.getIndex()) {
XSSFColor bgColor = (XSSFColor) cell.getCellStyle()
.getFillForegroundColorColor();
if (bgColor != null) {
byte[] rgb = bgColor.getRGB();
if (rgb != null && rgb.length == 3) {
cellPdf.setBackgroundColor(new BaseColor(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
}
}
}
}
private static void setCellAlignment(Cell cell, PdfPCell cellPdf) {
CellStyle cellStyle = cell.getCellStyle();
HorizontalAlignment horizontalAlignment = cellStyle.getAlignment();
VerticalAlignment verticalAlignment = cellStyle.getVerticalAlignment();
switch (horizontalAlignment) {
case LEFT:
cellPdf.setHorizontalAlignment(Element.ALIGN_LEFT);
break;
case CENTER:
cellPdf.setHorizontalAlignment(Element.ALIGN_CENTER);
break;
case JUSTIFY:
case FILL:
cellPdf.setVerticalAlignment(Element.ALIGN_JUSTIFIED);
break;
case RIGHT:
cellPdf.setHorizontalAlignment(Element.ALIGN_RIGHT);
break;
}
switch (verticalAlignment) {
case TOP:
cellPdf.setVerticalAlignment(Element.ALIGN_TOP);
break;
case CENTER:
cellPdf.setVerticalAlignment(Element.ALIGN_MIDDLE);
break;
case JUSTIFY:
cellPdf.setVerticalAlignment(Element.ALIGN_JUSTIFIED);
break;
case BOTTOM:
cellPdf.setVerticalAlignment(Element.ALIGN_BOTTOM);
break;
}
}
private static Font getCellStyle(Cell cell) throws DocumentException, IOException {
Font font = new Font();
CellStyle cellStyle = cell.getCellStyle();
org.apache.poi.ss.usermodel.Font cellFont = cell.getSheet()
.getWorkbook()
.getFontAt(cellStyle.getFontIndexAsInt());
short fontColorIndex = cellFont.getColor();
if (fontColorIndex != IndexedColors.AUTOMATIC.getIndex() && cellFont instanceof XSSFFont) {
XSSFColor fontColor = ((XSSFFont) cellFont).getXSSFColor();
if (fontColor != null) {
byte[] rgb = fontColor.getRGB();
if (rgb != null && rgb.length == 3) {
font.setColor(new BaseColor(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
}
}
}
if (cellFont.getItalic()) {
font.setStyle(Font.ITALIC);
}
if (cellFont.getStrikeout()) {
font.setStyle(Font.STRIKETHRU);
}
if (cellFont.getUnderline() == 1) {
font.setStyle(Font.UNDERLINE);
}
short fontSize = cellFont.getFontHeightInPoints();
font.setSize(fontSize);
if (cellFont.getBold()) {
font.setStyle(Font.BOLD);
}
String fontName = cellFont.getFontName();
if (FontFactory.isRegistered(fontName)) {
font.setFamily(fontName); // Use extracted font family if supported by iText
} else {
logger.warn("Unsupported font type: {}", fontName);
// - Use a fallback font (e.g., Helvetica)
font.setFamily("Helvetica");
}
return font;
}
public static void main(String[] args) throws DocumentException, IOException {
String excelFilePath = "src/main/resources/excelsample.xlsx";
String pdfFilePath = "src/main/resources/pdfsample.pdf";
convertExcelToPDF(excelFilePath, pdfFilePath);
}
}
@@ -0,0 +1,43 @@
package com.baeldung.pdfedition;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.pdfcleanup.CleanUpProperties;
import com.itextpdf.pdfcleanup.PdfCleanUpLocation;
import com.itextpdf.pdfcleanup.PdfCleanUpTool;
import com.itextpdf.pdfcleanup.PdfCleaner;
import com.itextpdf.pdfcleanup.autosweep.CompositeCleanupStrategy;
import com.itextpdf.pdfcleanup.autosweep.RegexBasedCleanupStrategy;
public class PdfContentRemover {
private static final String SOURCE = "src/main/resources/baeldung-modified.pdf";
private static final String DESTINATION = "src/main/resources/baeldung-cleaned.pdf";
public static void main(String[] args) throws IOException {
PdfReader reader = new PdfReader(SOURCE);
PdfWriter writer = new PdfWriter(DESTINATION);
PdfDocument pdfDocument = new PdfDocument(reader, writer);
removeContentFromDocument(pdfDocument);
pdfDocument.close();
}
private static void removeContentFromDocument(PdfDocument pdfDocument) throws IOException {
// 5.1. remove text
CompositeCleanupStrategy strategy = new CompositeCleanupStrategy();
strategy.add(new RegexBasedCleanupStrategy("Baeldung"));
PdfCleaner.autoSweepCleanUp(pdfDocument, strategy);
// 5.2. remove other areas
List<PdfCleanUpLocation> cleanUpLocations = Arrays.asList(new PdfCleanUpLocation(1, new Rectangle(10, 50, 90, 70)), new PdfCleanUpLocation(2, new Rectangle(35, 400, 100, 35)));
PdfCleanUpTool cleaner = new PdfCleanUpTool(pdfDocument, cleanUpLocations, new CleanUpProperties());
cleaner.cleanUp();
}
}
@@ -0,0 +1,86 @@
package com.baeldung.pdfedition;
import java.io.IOException;
import java.net.MalformedURLException;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.forms.fields.PdfTextFormField;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfTextAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.properties.UnitValue;
public class PdfEditor {
private static final String SOURCE = "src/main/resources/baeldung.pdf";
private static final String DESTINATION = "src/main/resources/baeldung-modified.pdf";
public static void main(String[] args) throws IOException {
PdfReader reader = new PdfReader(SOURCE);
PdfWriter writer = new PdfWriter(DESTINATION);
PdfDocument pdfDocument = new PdfDocument(reader, writer);
addContentToDocument(pdfDocument);
}
private static void addContentToDocument(PdfDocument pdfDocument) throws MalformedURLException {
// 4.1. add form
PdfFormField personal = PdfFormField.createEmptyField(pdfDocument);
personal.setFieldName("information");
PdfTextFormField name = PdfFormField.createText(pdfDocument, new Rectangle(35, 400, 100, 30), "name", "");
personal.addKid(name);
PdfAcroForm.getAcroForm(pdfDocument, true)
.addField(personal, pdfDocument.getFirstPage());
// 4.2. add new page
pdfDocument.addNewPage(1);
// 4.3. add annotation
PdfAnnotation ann = new PdfTextAnnotation(new Rectangle(40, 435, 0, 0)).setTitle(new PdfString("name"))
.setContents("Your name");
pdfDocument.getPage(2)
.addAnnotation(ann);
// create document form pdf document
Document document = new Document(pdfDocument);
// 4.4. add an image
ImageData imageData = ImageDataFactory.create("src/main/resources/baeldung.png");
Image image = new Image(imageData).scaleAbsolute(550, 100)
.setFixedPosition(1, 10, 50);
document.add(image);
// 4.5. add a paragraph
Text title = new Text("This is a demo").setFontSize(16);
Text author = new Text("Baeldung tutorials.");
Paragraph p = new Paragraph().setFontSize(8)
.add(title)
.add(" from ")
.add(author);
document.add(p);
// 4.6. add a table
Table table = new Table(UnitValue.createPercentArray(2));
table.addHeaderCell("#");
table.addHeaderCell("company");
table.addCell("name");
table.addCell("baeldung");
document.add(table);
// close the document
// this automatically closes the pdfDocument, which then closes automatically the pdfReader and pdfWriter
document.close();
}
}
@@ -0,0 +1,45 @@
package com.baeldung.pdfedition;
import java.io.IOException;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.parser.listener.IPdfTextLocation;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.pdfcleanup.PdfCleaner;
import com.itextpdf.pdfcleanup.autosweep.CompositeCleanupStrategy;
import com.itextpdf.pdfcleanup.autosweep.RegexBasedCleanupStrategy;
public class PdfTextReplacement {
private static final String SOURCE = "src/main/resources/baeldung-modified.pdf";
private static final String DESTINATION = "src/main/resources/baeldung-fixed.pdf";
public static void main(String[] args) throws IOException {
PdfReader reader = new PdfReader(SOURCE);
PdfWriter writer = new PdfWriter(DESTINATION);
PdfDocument pdfDocument = new PdfDocument(reader, writer);
replaceTextContentFromDocument(pdfDocument);
pdfDocument.close();
}
private static void replaceTextContentFromDocument(PdfDocument pdfDocument) throws IOException {
CompositeCleanupStrategy strategy = new CompositeCleanupStrategy();
strategy.add(new RegexBasedCleanupStrategy("Baeldung tutorials").setRedactionColor(ColorConstants.WHITE));
PdfCleaner.autoSweepCleanUp(pdfDocument, strategy);
for (IPdfTextLocation location : strategy.getResultantLocations()) {
PdfPage page = pdfDocument.getPage(location.getPageNumber() + 1);
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), page.getDocument());
Canvas canvas = new Canvas(pdfCanvas, location.getRectangle());
canvas.add(new Paragraph("HIDDEN").setFontSize(8)
.setMarginTop(0f));
}
}
}
@@ -0,0 +1,31 @@
package com.baeldung.pdfinfo;
import com.itextpdf.text.pdf.PdfReader;
import java.io.IOException;
import java.util.Map;
public class PdfInfoIText {
public static int getNumberOfPages(final String pdfFile) throws IOException {
PdfReader reader = new PdfReader(pdfFile);
int pages = reader.getNumberOfPages();
reader.close();
return pages;
}
public static boolean isPasswordRequired(final String pdfFile) throws IOException {
PdfReader reader = new PdfReader(pdfFile);
boolean isEncrypted = reader.isEncrypted();
reader.close();
return isEncrypted;
}
public static Map<String, String> getInfo(final String pdfFile) throws IOException {
PdfReader reader = new PdfReader(pdfFile);
Map<String, String> info = reader.getInfo();
reader.close();
return info;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.pdfinfo;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import java.io.File;
import java.io.IOException;
public class PdfInfoPdfBox {
public static int getNumberOfPages(final String pdfFile) throws IOException {
File file = new File(pdfFile);
PDDocument document = Loader.loadPDF(file);
int pages = document.getNumberOfPages();
document.close();
return pages;
}
public static boolean isPasswordRequired(final String pdfFile) throws IOException {
File file = new File(pdfFile);
PDDocument document = Loader.loadPDF(file);
boolean isEncrypted = document.isEncrypted();
document.close();
return isEncrypted;
}
public static PDDocumentInformation getInfo(final String pdfFile) throws IOException {
File file = new File(pdfFile);
PDDocument document = Loader.loadPDF(file);
PDDocumentInformation info = document.getDocumentInformation();
document.close();
return info;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

@@ -0,0 +1,43 @@
%PDF-1.4
%âãÏÓ
3 0 obj
<</Length 751/Filter/FlateDecode>>stream
xœ•WËRÛ0Ýû+î’.Puõ´–@Ÿ”R žÎtéi ¤Íc0d:ü}%K&a¢«daœãsïÑ‘tdªÓ¦’jn ™VXæ, îÞšÛêèG?íz¸˜=>ÁU{×¾kþTÇéqÚyÞðç høe¸çpŒj¨ÿ±©®«‡Š3'œBàL9.ü@ý]b}säŠú®º-<ŽŠ³ÃBi&bHåX}CiÅT††.àÜûñÙ³5üË
w’ üÐF4?ŒÍKѼ¼É–$îägW&Iš$hDq
'GÈìJ¢Ð(‰B£$
H®ojGȯú]Iš$hD IÅõMµ-¹D I&Iš$Q\ßÔï$M4I"Ð$‰âú¦øb`fyShD I&I;èuH_Ÿ þ‹`-ãaK;h1zUˆ^3\×5„+:órõ9st¹b!i9Ü…dݪ…F±ÚV,Fü×ùŠ"T”`•|{ųõãÓjÑõcÅ—Z¶fJêŠl]^¬5“õa#lVOí<_N9ôq~X¹«v6¥ÄEŒ• *
Xà!ãĬ)òu‹©^3Oû3¤lÈ_ºïÉrú íšp@8Æu‰¯
«ó\ͳ%ê/Ò'ã4E
Ìè“(ùT`ŸwËå3|Y}*ðýêv´OÒ–¸—´Q–$É=FÌ 9£dÑ(ºïÅzö?)›ÛV›mÀ÷úD·.ø¤ER{|¢™Ñ'Uô‰fë–¼*/(í^;åQf⛥DéýaOH¦K{° ¢°ÇPÏìùW–ÅßoÂÛk=˜ƒmÒÁ¢BçÕªáfÎ=ÿŠ‹þ‘]“é^ÑdbxÉdšý½]®»9Lœ¶7gNÞkºŒÙrjÁ`$²yƒÁ>W7û›²Át¯h°)þó˳ÏîÛ~>ëà†íœç‘o“ß÷};Ý7´\©‘Li*hêöTüˆ
endstream
endobj
5 0 obj
<</Type/Page/MediaBox[0 0 595 842]/Resources<</Font<</F1 1 0 R/F2 2 0 R>>>>/Contents 3 0 R/Parent 4 0 R>>
endobj
1 0 obj
<</Type/Font/Subtype/Type1/BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding>>
endobj
2 0 obj
<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>
endobj
4 0 obj
<</Type/Pages/Count 1/Kids[5 0 R]>>
endobj
6 0 obj
<</Type/Catalog/Pages 4 0 R>>
endobj
7 0 obj
<</Producer(iText® 5.5.13.3 ©2000-2022 iText Group NV \(AGPL-version\))/CreationDate(D:20231213174247+08'00')/ModDate(D:20231213174247+08'00')>>
endobj
xref
0 8
0000000000 65535 f
0000000954 00000 n
0000001047 00000 n
0000000015 00000 n
0000001135 00000 n
0000000833 00000 n
0000001186 00000 n
0000001231 00000 n
trailer
<</Size 8/Root 6 0 R/Info 7 0 R/ID [<6a28b1036b62f3808f3bfb62a88a5239><6a28b1036b62f3808f3bfb62a88a5239>]>>
@@ -0,0 +1,31 @@
package com.baeldung.pdfinfo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.io.IOException;
import java.util.Map;
import org.junit.jupiter.api.Test;
class PdfInfoITextUnitTest {
private static final String PDF_FILE = "src/test/resources/input.pdf";
@Test
void givenPdf_whenGetNumberOfPages_thenOK() throws IOException {
assertEquals(4, PdfInfoIText.getNumberOfPages(PDF_FILE));
}
@Test
void givenPdf_whenIsPasswordRequired_thenOK() throws IOException {
assertFalse(PdfInfoIText.isPasswordRequired(PDF_FILE));
}
@Test
void givenPdf_whenGetInfo_thenOK() throws IOException {
Map<String, String> info = PdfInfoIText.getInfo(PDF_FILE);
assertEquals("LibreOffice 4.2", info.get("Producer"));
assertEquals("Writer", info.get("Creator"));
}
}
@@ -0,0 +1,31 @@
package com.baeldung.pdfinfo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.junit.jupiter.api.Test;
import java.io.IOException;
class PdfInfoPdfBoxUnitTest {
private static final String PDF_FILE = "src/test/resources/input.pdf";
@Test
void givenPdf_whenGetNumberOfPages_thenOK() throws IOException {
assertEquals(4, PdfInfoPdfBox.getNumberOfPages(PDF_FILE));
}
@Test
void givenPdf_whenIsPasswordRequired_thenOK() throws IOException {
assertFalse(PdfInfoPdfBox.isPasswordRequired(PDF_FILE));
}
@Test
void givenPdf_whenGetInfo_thenOK() throws IOException {
PDDocumentInformation info = PdfInfoPdfBox.getInfo(PDF_FILE);
assertEquals("LibreOffice 4.2", info.getProducer());
assertEquals("Writer", info.getCreator());
}
}