add itext WaterMark to android java pdf - java

I need to add an itext watermark to my pdf android java pdf file
my sample current code for creating the pdf file:
File docsFolder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "osary/estmara");
String currentDate = new SimpleDateFormat("dd-MM-yyyy_hh_mm_aaa", Locale.getDefault()).format(new Date());
String pdfname = myEstmaraa.getTalabId() + "_" + currentDate + ".pdf";
pdfFile = new File(docsFolder, pdfname);
OutputStream output = new FileOutputStream(pdfFile);
Document document = new Document(PageSize.A4);
document.setMargins(5, 5, 5, 5);
PdfWriter PdfWriters = PdfWriter.getInstance(document, output);
PdfWriters.createXmpMetadata();
PdfWriters.setTagged();
document.open();
//todo 2 preparing Header and directions and margin row 0
PdfPTable tableForRowZero = new PdfPTable(new float[]{1});
tableForRowZero.setSpacingBefore(5);
tableForRowZero.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
tableForRowZero.getDefaultCell().setFixedHeight(34);
tableForRowZero.setTotalWidth(PageSize.A4.getWidth());
tableForRowZero.setWidthPercentage(100);
tableForRowZero.setHeaderRows(0);
tableForRowZero.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
cellss = new PdfPCell(new Phrase("رقم الاستمارة", FONT2));
cellss.setHorizontalAlignment(Element.ALIGN_CENTER);
cellss.setVerticalAlignment(Element.ALIGN_CENTER);
cellss.setBackgroundColor(BaseColor.GRAY);
tableForRowZero.addCell(cellss);
tableForRowZero.setHeaderRows(0);
cellss = new PdfPCell(new Phrase(String.valueOf(myEstmaraa.getTalabId()), FONT2));
cellss.setHorizontalAlignment(Element.ALIGN_CENTER);
cellss.setVerticalAlignment(Element.ALIGN_CENTER);
tableForRowZero.addCell(cellss);
document.add(tableForRowZero);
document.close();
i have tried this code but it for desktop java:
enter link description here
and the problem that i faced is this line:
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
when i change it to android i face a problem, i tried it like:
com.itextpdf.kernel.pdf.PdfDocument pdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(pdfFile.getPath()),new PdfWriter(pdfFile.getPath()));
it gives me this hint:
Cannot resolve constructor 'PdfWriter(java.lang.String)'
the code i tried to make watermark:
com.itextpdf.kernel.pdf.PdfDocument pdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(pdfFile.getPath()),new PdfWriter(pdfFile.getPath()));
PdfCanvas under = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(), new PdfResources(), pdfDoc);
PdfFont font = PdfFontFactory.createFont(FontProgramFactory.createFont(StandardFonts.HELVETICA));
com.itextpdf.layout.element.Paragraph paragraph2 = new com.itextpdf.layout.element.Paragraph("This watermark is added UNDER the existing content")
.setFont(font)
.setFontSize(15);
Canvas canvasWatermark1 = new Canvas(under, pdfDoc.getDefaultPageSize())
.showTextAligned(paragraph2, 297, 550, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
canvasWatermark1.close();
PdfCanvas over = new PdfCanvas(pdfDoc.getFirstPage());
over.setFillColor(ColorConstants.BLACK);
paragraph2 = new com.itextpdf.layout.element.Paragraph("This watermark is added ON TOP OF the existing content")
.setFont(font)
.setFontSize(15);
Canvas canvasWatermark2 = new Canvas(over, pdfDoc.getDefaultPageSize())
.showTextAligned(paragraph2, 297, 500, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
canvasWatermark2.close();
paragraph2 = new com.itextpdf.layout.element.Paragraph("This TRANSPARENT watermark is added ON TOP OF the existing content")
.setFont(font)
.setFontSize(15);
over.saveState();
// Creating a dictionary that maps resource names to graphics state parameter dictionaries
PdfExtGState gs1 = new PdfExtGState();
gs1.setFillOpacity(0.5f);
over.setExtGState(gs1);
Canvas canvasWatermark3 = new Canvas(over, pdfDoc.getDefaultPageSize())
.showTextAligned(paragraph2, 297, 450, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
canvasWatermark3.close();
over.restoreState();
i tried also to add png image and set its opacity but it cover the content
try {
com.itextpdf.text.Image image1_emp_osary = null;
Drawable d_emp_osary = getResources().getDrawable(R.drawable.ketm_estmara);
BitmapDrawable bitDw_emp_osary = ((BitmapDrawable) d_emp_osary);
Bitmap bmp_emp_osary = bitDw_emp_osary.getBitmap();
ByteArrayOutputStream stream_emp_osary = new ByteArrayOutputStream();
bmp_emp_osary.compress(Bitmap.CompressFormat.PNG, 100, stream_emp_osary);
image1_emp_osary = com.itextpdf.text.Image.getInstance(stream_emp_osary.toByteArray());
image1_emp_osary.scaleToFit(200, 200);
image1_emp_osary.setAlignment(Element.ALIGN_BOTTOM);
image1_emp_osary.setSpacingBefore(200);
image1_emp_osary.setTransparency(new int[]{5, 5});
document.add(new Chunk(image1_emp_osary, 0, 200));
PdfContentByte canvas = PdfWriters.getDirectContentUnder();
PdfGState state = new PdfGState();
state.setFillOpacity(0.6f);
canvas.setGState(state);
canvas.addImage(image1_emp_osary);
canvas.restoreState();
} catch (Exception e) {
e.printStackTrace();
}

i have solved it,
the idea is:
1.we need to save the file with out water mark ,and that was easy:
File docsFolder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "osary/estmara");
String currentDate = new SimpleDateFormat("dd-MM-yyyy_hh_mm_aaa", Locale.getDefault()).format(new Date());
String pdfname = myEstmaraa.getTalabId() + "_" + currentDate + ".pdf";
pdfFile = new File(docsFolder, pdfname);
OutputStream output = new FileOutputStream(pdfFile);
Document document = new Document(PageSize.A4);
document.setMargins(5, 5, 5, 5);
PdfWriter PdfWriters = PdfWriter.getInstance(document, output);
PdfWriters.createXmpMetadata();
PdfWriters.setTagged();
document.open();
//todo 2 preparing Header and directions and margin row 0
PdfPTable tableForRowZero = new PdfPTable(new float[]{1});
tableForRowZero.setSpacingBefore(5);
tableForRowZero.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
tableForRowZero.getDefaultCell().setFixedHeight(34);
tableForRowZero.setTotalWidth(PageSize.A4.getWidth());
tableForRowZero.setWidthPercentage(100);
tableForRowZero.setHeaderRows(0);
tableForRowZero.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
cellss = new PdfPCell(new Phrase("رقم الاستمارة", FONT2));
cellss.setHorizontalAlignment(Element.ALIGN_CENTER);
cellss.setVerticalAlignment(Element.ALIGN_CENTER);
cellss.setBackgroundColor(BaseColor.GRAY);
tableForRowZero.addCell(cellss);
tableForRowZero.setHeaderRows(0);
cellss = new PdfPCell(new Phrase(String.valueOf(myEstmaraa.getTalabId()), FONT2));
cellss.setHorizontalAlignment(Element.ALIGN_CENTER);
cellss.setVerticalAlignment(Element.ALIGN_CENTER);
tableForRowZero.addCell(cellss);
document.add(tableForRowZero);
document.close();
2.we will open the file but we can not override it directly,
so:
a. we will save it in a temp file with the watermark and close it:
File tempFile = new File(docsFolder.getPath(), "temp.pdf");
com.itextpdf.kernel.pdf.PdfWriter TempWriter = new com.itextpdf.kernel.pdf.PdfWriter(tempFile);
String font = "/res/font/arialbd.ttf";
PdfFontFactory.register(font);
FontProgram fontProgram = FontProgramFactory.createFont(font, true);
PdfFont f = PdfFontFactory.createFont(fontProgram, PdfEncodings.IDENTITY_H);
LanguageProcessor languageProcessor = new ArabicLigaturizer();
com.itextpdf.kernel.pdf.PdfDocument tempPdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(pdfFile.getPath()), TempWriter);
com.itextpdf.layout.Document TempDoc = new com.itextpdf.layout.Document(tempPdfDoc);
com.itextpdf.layout.element.Paragraph paragraph0 = new com.itextpdf.layout.element.Paragraph(languageProcessor.process("الاستماره الالكترونية--الاستماره الالكترونية--الاستماره الالكترونية--الاستماره الالكترونية"))
.setFont(f).setBaseDirection(BaseDirection.RIGHT_TO_LEFT)
.setFontSize(15);
Drawable d_ketm_estmara = getResources().getDrawable(R.drawable.ketm_estmara);
Bitmap bitDw_estmara = ((BitmapDrawable) d_ketm_estmara).getBitmap();
ByteArrayOutputStream stream_estmara = new ByteArrayOutputStream();
bitDw_estmara.compress(Bitmap.CompressFormat.PNG, 100, stream_estmara);
byte[] data = stream_estmara.toByteArray();
ImageData img = ImageDataFactory.create(data);
PdfExtGState gs1 = new PdfExtGState().setFillOpacity(0.2f);
for (int i = 1; i <= tempPdfDoc.getNumberOfPages(); i++) {
PdfPage pdfPage = tempPdfDoc.getPage(i);
com.itextpdf.kernel.geom.Rectangle pageSize = pdfPage.getPageSize();
float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
float y = (pageSize.getTop() + pageSize.getBottom()) / 3;
PdfCanvas over = new PdfCanvas(pdfPage);
over.saveState();
over.setExtGState(gs1);
TempDoc.showTextAligned(paragraph0, 300, 760, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
float leftImage = 20;
float bottomImage = 120;
float rightImage = 550;
float topImage = 720;
over.addImageWithTransformationMatrix(img, rightImage, 0, 0, topImage, leftImage, bottomImage, true);
over.restoreState();
}
TempDoc.close();
tempPdfDoc.close();
b. we will open the temp file and save it with the old name:
com.itextpdf.kernel.pdf.PdfDocument pdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(tempFile.getPath()), new com.itextpdf.kernel.pdf.PdfWriter(new File(docsFolder.getPath(), pdfname)));
com.itextpdf.layout.Document doc = new com.itextpdf.layout.Document(pdfDoc);
doc.close();
pdfDoc.close();

Related

how to insert paragraphs with different positions - itext

The drawing of the table is done correctly but it gets wrong as the data is repeated.
the barcode has to be like this to avoid errors from employees checking wrong codes.
The ideal would be A picture speaks a thousand words.
My function:
Document documentoPDF = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(documentoPDF, new FileOutputStream("c:\\exporta_Celso\\contagem_" + jComboBox1.getSelectedItem().toString() + ".pdf"));
documentoPDF.open();
documentoPDF.setPageSize(PageSize.A4);
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100);
table.setTotalWidth(documentoPDF.getPageSize().getWidth());
for (int i = 0; i < itens.size(); i++) {
System.out.println(((List) itens.get(i)).get(0).toString());
System.out.println(((List) itens.get(i)).get(1).toString());
String item = ((List) itens.get(i)).get(1).toString();
BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
String barCodeBruto = ((List) itens.get(i)).get(0).toString();
String barCode = null;
if (barCodeBruto.length() != 13) {
barCode = ("0000000000000" + barCodeBruto).substring(barCodeBruto.length());
} else {
barCode = barCodeBruto;
}
codeEAN.setCode(barCode);
PdfContentByte cb = writer.getDirectContent();
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);
PdfPCell cellBar = new PdfPCell(imageEAN);
PdfPCell cellDesc = new PdfPCell(new Paragraph(item));
PdfPCell cellQtd = new PdfPCell(new Paragraph("QTD."));
cellBar.setPadding(3);
cellBar.setUseDescender(true);
cellBar.setUseAscender(true);
cellDesc.setPadding(3);
cellDesc.setUseDescender(true);
cellDesc.setUseAscender(true);
cellQtd.setPadding(3);
cellQtd.setUseDescender(true);
cellQtd.setUseAscender(true);
float height = table.calculateHeights();
float width = documentoPDF.getPageSize().getWidth();
if (i % 2 == 0) {
float[] widths = new float[]{145f, width - 36 - 10f, 80f};
table.setWidths(widths);
table.addCell(cellBar);
table.addCell(cellDesc);
table.addCell(cellQtd);
}else{
float[] widths = new float[]{80f, width - 36 - 10f, 145f};
table.setWidths(widths);
table.addCell(cellQtd);
table.addCell(cellDesc);
table.addCell(cellBar);
}
PdfContentByte canvas = writer.getDirectContent();
ColumnText columnText = new ColumnText(canvas);
columnText.setSimpleColumn(36, 756 - height, width - 36, 36);
columnText.addElement(table);
columnText.go();
}
} catch (DocumentException de) {
de.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
documentoPDF.close();
}
I solved it by creating a parent table outside the looping.
PdfPTable tableFinal = new PdfPTable(1);
tableFinal.setWidthPercentage(100);
tableFinal.setTotalWidth(documentoPDF.getPageSize().getWidth());
tableFinal.addCell(table);
PdfContentByte canvas = writer.getDirectContent();
ColumnText columnText = new ColumnText(canvas);
columnText.setSimpleColumn(36, 756 - height, width - 36, 36);
columnText.addElement(tableFinal);
columnText.go();

Is it Possible to get the header and footer from a PDF document using IText?

I'm merging two separate PDF files into a single PDF file, using IText. But the problem is i need to replace the headers and footers of first page in all the pages. Is it possible to segregate the header , footer and the body content of the PDF Itext ?
I'm using Itext 5
So far I have done
PdfReader reader1 = new PdfReader("C:\\Users\\user1\\Downloads\\generatedSample.pdf");
PdfReader reader2 = new PdfReader("C:\\Users\\user1\\Downloads\\tobeconv.pdf");
Document document = new Document();
document.addHeader("Header Text", "");
FileOutputStream fos = new FileOutputStream("C:\\Users\\user1\\Downloads\\MergeFile.pdf");
PdfCopy copy = new PdfCopy(document, fos);
document.open();
PdfImportedPage page;
PdfCopy.PageStamp stamp;
Phrase phrase;
BaseFont bf = BaseFont.createFont();
Font font = new Font(bf, 9);
int n = reader1.getNumberOfPages();
for (int i = 1; i <= reader1.getNumberOfPages(); i++)
{
page = copy.getImportedPage(reader1, i);
stamp = copy.createPageStamp(page);
// phrase = new Phrase("page"+i+"of "+n,font);
ColumnText.showTextAligned(stamp.getOverContent(), Element.ALIGN_CENTER, null, 520, 5, 0);
stamp.alterContents();
copy.addPage(page);
}
for (int i = 1; i <= reader2.getNumberOfPages(); i++) {
page = copy.getImportedPage(reader2, i);
stamp = copy.createPageStamp(page);
// phrase = new Phrase("page " + (n + i), font);
ColumnText.showTextAligned(stamp.getOverContent(),
Element.ALIGN_CENTER, null, 520, 5, 0);
stamp.alterContents();
copy.addPage(page);
}
Any suggestions?
Thanks for the help in advance

How to add a table of contents with page numbers to a RTF

I have sucessfully generated the table of contents but how to add respective page numbers. I am using the RtfWriter2 of iText to create documents.
I have tried below code to add table of contents but no luck.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document doc = new Document();
RtfWriter2 writer2 = RtfWriter2.getInstance(doc, baos);
try {
writer2.setAutogenerateTOCEntries(true);
Table headerTable = new Table(3);
headerTable.addCell("Test Cell 1");
headerTable.addCell("Test Cell 2");
headerTable.addCell("Test Cell 3");
HeaderFooter header = new RtfHeaderFooter(headerTable);
RtfHeaderFooterGroup footer = new RtfHeaderFooterGroup();
doc.open();
Paragraph p = new Paragraph();
p.add(new RtfTableOfContents("UPDATE ME!"));
doc.add(p);
p = new Paragraph("", new RtfFont("Staccato222 BT"));
p.add(new Chunk("Hello! "));
p.add(new Chunk("How do you do?"));
doc.add(p);
p.setAlignment(Element.ALIGN_RIGHT);
doc.add(p);
Chunk c = new Chunk("");
c.setNewPage();
doc.add(c);
for (int i = 0; i < 300; i++) {
doc.add(new Paragraph( "Dummy line to get multi-page document. Line " + (i + 1)));
}
} catch (Exception e) {
e.printStackTrace();
}
doc.close();
return baos;
Below is the output I am trying for:
Table of contents
History 1
Intro 2

JFreeChart low performance for MeterPlot

I'm implementing a web application using spring 4.2.5 and jasperreports 6.4.3.
This app is supposed to generate a pdf file as output. There are three jrxml files:
firstpage.jrxml: contains logo and some titles
intro.jsrxml: contains some texts and a table of items overview
items.jrxml: contains some texts and an image to show a JFree MeterPlot output buffer image.
The code:
public void export() {
JasperPrint firstPagePrint = ...;
JasperPrint introPrint = ...;
List<JasperPrint> itemsPrints = new LinkedList<JapserPrint>();
List<Item> items = ...;
for (int i = 0; i < items.size(); i++) {
Item item = items.get(i);
MeterPlot meterPlot = new MeterPlot(new DefaultValueDataset(item.getValue()));
meterPlot.setRange(new Range(item.getMinValue(), item.getMaxValue()));
meterPlot.addInterval(new MeterInterval("bad", new Range(item.getMinValue(), item.getSect1()),
Color.red, new BasicStroke(2f), Color.red));
meterPlot.addInterval(new MeterInterval("weak", new Range(item.getSect1(), item.getSect2()),
Color.orange, new BasicStroke(2f), Color.orange));
meterPlot.addInterval(new MeterInterval("average", new Range(item.getSect2(), item.getSect3()),
Color.yellow, new BasicStroke(2f), Color.yellow));
meterPlot.addInterval(new MeterInterval("good", new Range(item.getSect3(), item.getSect4()),
Color.green, new BasicStroke(2f), Color.green));
meterPlot.addInterval(new MeterInterval("excellent", new Range(item.getSect4(), item.getMaxValue()),
Color.black, new BasicStroke(2f), Color.BLUE));
JFreeChart jFreeChart = new JFreeChart(item.getTitle(), meterPlot);
BufferedImage bufferedImage = jFreeChart.createBufferedImage(555, 250);
String tmpFile = FileService.JASPER + Util.randomNumeralString(20) + ".png";
ImageIO.write(bufferedImage, "png", new File(tmpFile));
itemAnalysisParams.put("chartImage", tmpFile);
analysisPrints.add(JasperFillManager.fillReport(ITEM_ANALYSIS, itemAnalysisParams, new JREmptyDataSource()));
}
...export pdf by jasper report prints
}
Notice:
sect1, sect2, sect3 and sect4 are internal limitation for intervals.
sect = (maxValue - minValue) * 20 / 100
sect1 = this.minValue + sect
sect2 = this.sect1 + sect
sect3 = this.sect2 + sect
sect4 = this.sect3 + sect
The problem:
The line BufferedImage bufferedImage = jFreeChart.createBufferedImage(555, 250); takes a long time- about 15min- to create image and it repeats for about 45 items and takes 15min*45 total time to generate report.
In advance, I appreciate any help.

Affixing digital signature on a pdf

I am trying to affix a digital signature on a pdf document.
I am able to affix the signature on the pdf but the signature is not visible. I tried a lot looked at so many codes (How to make a signature visible on a document) making signature visible but somehow not able to do .Here is the code which i am using to affix the signature on the pdf.
String inputPDFlocation = INPUT_PDF_BASEPATH + inputPDFfilename;
String outputPDFlocation = OUTPUT_PDF_BASEPATH + inputPDFfilename;
PdfReader reader = new PdfReader(inputPDFlocation); // input PDF
PdfStamper stamper = PdfStamper.createSignature(reader, new FileOutputStream(outputPDFlocation), '\0', null, true);
// Finding the size of the page, and determining the location of signature:
Rectangle cropBox = reader.getCropBox(1); // Gets the 1st page
float width = 78;
float height = 34;
Rectangle rectangle;
// Top left
rectangle = new Rectangle(cropBox.getLeft(), cropBox.getTop(height), cropBox.getLeft(width), cropBox.getTop());
// Creating the appearance
PdfSignatureAppearance sap = stamper.getSignatureAppearance();
sap.setReason(SIGNATURE_REASON);
sap.setLocation(SIGNATURE_LOCATION);
sap.setVisibleSignature(rectangle, 1, sap.getNewSigName()); // new Rectangle(36, 748, 144, 780)
ExternalDigest externalDigest = new BouncyCastleDigest();
int estimatedSize = 8192;
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
dic.setReason(sap.getReason());
dic.setLocation(sap.getLocation());
dic.setSignatureCreator(sap.getSignatureCreator());
dic.setContact(sap.getContact());
// Adding a buffer between the signature generation and the certificate start valid time.
Calendar cal = sap.getSignDate();
cal.add(Calendar.MINUTE, 1);
dic.setDate(new PdfDate(cal)); // time-stamp will over-rule this
sap.setCryptoDictionary(dic);
HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));
sap.preClose(exc);
String hashAlgorithm = DigestAlgorithms.SHA256;
InputStream data = sap.getRangeStream();
byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm));
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
sb.append(Integer.toString((hash[i] & 0xff) + 0x100, 16).substring(1));
}
// 5. Setting Document hash
esign.setInput(sb.toString());
StringWriter eSignXML = new StringWriter();
try {
JAXBContext.newInstance(Esign.class).createMarshaller().marshal(esign, eSignXML);
} catch (Exception ex) {
logger.error("There was an error converting <Esign> XML to String: {}", ex.getMessage());
}
// 7. Get the digital signer, and sign the XML
DigitalSigner ds = getDigitalSigner();
if (ds == null) {
return eSignResponse;
}
String signedEsignXML = ds.signXML(eSignXML.toString(), true);
// 8. Make a request
String responseXML = null;
Response response = HTTPClient.postRequestWithXmlPayloadOverTLS(eSignConfig.get(URL_ESIGN_SERVER), null, null, signedEsignXML, false);
if (response != null) {
if (Response.Status.Family.familyOf(response.getStatus()) == Response.Status.Family.SUCCESSFUL) {
responseXML = response.getEntity().toString();
}
}
// 9. Parse the response
EsignResp esignResp = XMLUtil.parseXML(responseXML, EsignResp.class);
if (esignResp != null) {
if (esignResp.getStatus() != null && esignResp.getStatus().equalsIgnoreCase("1")) {
eSignResponse.setStatus(1);
// If response is a SUCCESS, affix the signature ...
String pkcs7Response = esignResp.getPkcs7Response();
CMSSignedData cms = new CMSSignedData(Base64.decodeBase64(pkcs7Response.getBytes()));
byte[] paddedSig = new byte[estimatedSize];
System.arraycopy(cms.getEncoded(), 0, paddedSig, 0, cms.getEncoded().length);
PdfDictionary dic2 = new PdfDictionary();
dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
sap.close(dic2);
}
You use a 0x0 rectangle for the visualization:
// Finding the size of the page, and determining the location of signature:
Rectangle cropBox = reader.getCropBox(1); // Gets the 1st page
float width = 0;
float height = 0;
Rectangle rectangle;
// Top left
rectangle = new Rectangle(cropBox.getLeft(), cropBox.getTop(height), cropBox.getLeft(width), cropBox.getTop());
[...]
sap.setVisibleSignature(rectangle, 1, sap.getNewSigName()); // new Rectangle(36, 748, 144, 780)
Unless you choose positive values for width and height, you will never see a signature visualization.

Categories