table header in pdf getting displayed using itextpdf5.1.1 but not in itextpdf5.5.3 - pdf

We have generated a pdf in landscape mode with header and footer as part of the pdf. The header table and footer display fine in pdf using itextpdf5.1.1 jar. However when we update the jar to 5.5.3, the header table does not show only the footer shows. Below is the code snippet.
document = new Document(PageSize.A4.rotate(), 20, 20, 75, 20);
PdfCopy copy = new PdfCopy(document, new FileOutputStream(strPDFFile));
document.open();
PdfReader pdfReaderIntermediate =
new PdfReader(strIntermediatePDFFile);
numberOfPages = pdfReaderIntermediate.getNumberOfPages();
Font ffont = new Font(Font.FontFamily.UNDEFINED, 7, Font.NORMAL);
System.out.println("###### No. of Pages: " + numberOfPages);
for (int j = 0; j < numberOfPages; ) {
page = copy.getImportedPage(pdfReaderIntermediate, ++j);
stamp = copy.createPageStamp(page);
Phrase footer =
new Phrase(String.format("%d of %d", j, numberOfPages), ffont);
ColumnText.showTextAligned(stamp.getUnderContent(),
Element.ALIGN_CENTER, footer,
(document.right() - document.left()) /
2 + document.leftMargin(),
document.bottom() - 10, 0);
if (j != 1) {
headerTable = new PdfPTable(2);
headerTable.setTotalWidth(700);
headerTable.getDefaultCell().setFixedHeight(10);
headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
headerTable.addCell(new Phrase(String.format(header1), ffont));
headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
headerTable.addCell(new Phrase(String.format(header2), ffont));
headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
headerTable.addCell(new Phrase(String.format(header3), ffont));
headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
headerTable.addCell(new Phrase(String.format(header5, j),
ffont));
headerTable.completeRow();
headerTable.writeSelectedRows(0, 5, 60.5f, 550,
stamp.getUnderContent());
}
stamp.alterContents();
copy.addPage(page);
}
document.close();
When we change the jar from 5.1.1 to 5.5.3 the header is lost. May be a change is needed in the way we call the header for the new jar.
Any inputs will be well appreciated.
Thanks.

You have cells with default padding (i.e. 2) and height 10, and you try to insert text at height 7. But 2 (top margin) + 7 (text height) + 2 (bottom margin) = 11, i.e. more than fits into your cell height 10. Thus, the text does not fit and is not displayed.
You can fix this by either
using a smaller font, e.g. 6, or
using a heigher cell, e.g. 11, or
using a smaller padding, e.g. 1:
headerTable.getDefaultCell().setPadding(1);
With any of these changes, your header shows.
I don't know in which way iText 5.1.1 handled this differently, but the behavior of current iText versions makes sense.

Related

When using iText to generate a PDF, if I need to switch fonts many times the file size becomes too large

I have a section of my PDF in which I need to use one font for its unicode symbol and the rest of the paragraph should be a different font. (It is something like "1. a 2. b 3. c" where "1." is the unicode symbol/font and "a" is another font) I have followed the method Bruno describes here: iText 7: How to build a paragraph mixing different fonts? and it works fine to generate the PDF. The issue is that the file size of the PDF goes from around 20MB to around 100MB compared to using only one font and one Text element. This section is used repeatedly in the document thousands of times. I am wondering if there is a way to reduce the impact of switching fonts or to reduce the file size of the entire document in some way.
Style creation pseudocode:
Style style1 = new Style();
Style style2 = new Style();
PdfFont font1 = PdfFontFactory.createFont(FontProgramFactory.createFont(fontFile1), PdfEncodings.IDENTITY_H, true);
style1.setFont(font1).setFontSize(8f).setFontColor(Color.DARK_GRAY);
PdfFont font2 = PdfFontFactory.createFont(FontProgramFactory.createFont(fontFile2), "", false);
style2.setFont(font2).setFontSize(8f).setFontColor(Color.DARK_GRAY);
Writing text/paragraph pseudocode:
Div div = new Div().setPaddingLeft(3).setMarginBottom(0).setKeepTogether(true);
Paragraph paragraph = new Paragraph();
loop up to 25 times: {
Text unicodeText = new Text(unicodeSymbol + " ").addStyle(style1);
paragraph.add(unicodeText);
Text plainText = new Text(plainText + " ").addStyle(style2);
paragraph.add(plainText);
}
div.add(paragraph);
This writing of text/paragraph is done thousands of times and makes up most of the document. Basically the document consists of thousands of "buildings" that have corresponding codes and the codes have categories. I need to have the index for the category as the unicode symbol and then all of the corresponding codes within the paragraph for the building.
Here is reproducable code:
float offSet = 50;
Integer leading = 10;
DateFormat format = new SimpleDateFormat("yyyy_MM_dd_kkmmss");
String formattedDate = format.format(new Date());
String path = "/tmp/testing_pdf_"+formattedDate + ".pdf";
File targetPdfFile = new File(path);
PdfWriter writer = new PdfWriter(path, new WriterProperties().addXmpMetadata());
PdfDocument pdf = new PdfDocument(writer);
pdf.setTagged();
PageSize pageSize = PageSize.LETTER;
Document document = new Document(pdf, pageSize);
document.setMargins(offSet, offSet, offSet, offSet);
byte[] font1file = IOUtils.toByteArray(FileUtility.getInputStreamFromClassPath("fonts/Garamond-Premier-Pro-Regular.ttf"));
byte[] font2file = IOUtils.toByteArray(FileUtility.getInputStreamFromClassPath("fonts/Quivira.otf"));
PdfFont font1 = PdfFontFactory.createFont(FontProgramFactory.createFont(font1file), "", true);
PdfFont font2 = PdfFontFactory.createFont(FontProgramFactory.createFont(font2file), PdfEncodings.IDENTITY_H, true);
Style style1 = new Style().setFont(font1).setFontSize(8f).setFontColor(Color.DARK_GRAY);
Style style2 = new Style().setFont(font2).setFontSize(8f).setFontColor(Color.DARK_GRAY);
float columnGap = 5;
float columnWidth = (pageSize.getWidth() - offSet * 2 - columnGap * 2) / 3;
float columnHeight = pageSize.getHeight() - offSet * 2;
Rectangle[] columns = {
new Rectangle(offSet, offSet, columnWidth, columnHeight),
new Rectangle(offSet + columnWidth + columnGap, offSet, columnWidth, columnHeight),
new Rectangle(offSet + columnWidth * 2 + columnGap * 2, offSet, columnWidth, columnHeight)};
document.setRenderer(new ColumnDocumentRenderer(document, columns));
for (int j = 0; j < 5000; j++) {
Div div = new Div().setPaddingLeft(3).setMarginBottom(0).setKeepTogether(true);
Paragraph paragraph = new Paragraph().setFixedLeading(leading);
// StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 26; i++) {
paragraph.add(new Text("\u3255 ").addStyle(style2));
paragraph.add(new Text("test ").addStyle(style1));
// stringBuilder.append("\u3255 ").append(" test ");
}
// paragraph.add(stringBuilder.toString()).addStyle(style2);
div.add(paragraph);
document.add(div);
}
document.close();
In creating the reproducible code I have found this this is related to the document being tagged. If you remove the line that marks it as tagged it reduces the file size greatly.
You can also reduce the file size by using the commented out string builder with one font instead of two. (Comment out the two "paragraph.add"s in the for-loop) This mirrors the issue I have in my code.
The problem is not in fonts themselves. The issues comes from the fact that you are creating a tagged PDF. Tagged documents have a lot of PDF objects in them that need a lot of space in the file.
I wasn't able to reproduce your 20MB vs 100MB results. On my machine whether with one font or with two fonts, but with two Text elements, the resultant file size is ~44MB.
To compress file when creating large tagged documents, you should use full compression mode which compresses all PDF objects, not only streams.
To activate full compression mode, create a PdfWriter instance with WriterProperties:
PdfWriter writer = new PdfWriter(outFileName,
new WriterProperties().setFullCompressionMode(true));
This setting reduced the file size for me from >40MB to ~5MB.
Please note that you are using iText 7.0.x while 7.1.x line has already been released and is now the main line of iText, so I recommend that you update to the latest version.

Unable to add margins in iTextSharp document having images

Requirement:
A large image (dynamic) needs to be split and shown in PDF pages. If image can't be accomodated in one page then we need to add another page and try to fit the remaining portion and so on.
So far I am able to split the image in multiple pages, however it appears that they are completely ignoring the margin values and so images are shown without any margins.
Please see below code:
string fileStringReplace = imageByteArray.Replace("data:image/jpeg;base64,", "");
Byte[] imageByte = Convert.FromBase64String(fileStringReplace);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageByte);
float w = image.ScaledWidth;
float h = image.ScaledHeight;
float cropHeight = 1500f;
iTextSharp.text.Rectangle page = new iTextSharp.text.Rectangle(1150f, cropHeight);
var x = page.Height;
Byte[] created;
iTextSharp.text.Document document = new iTextSharp.text.Document(page, 20f, 20f, 20f, 40f); --This has no impact
using (var outputMemoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(document, outputMemoryStream);
writer.CloseStream = false;
document.Open();
PdfContentByte canvas = writer.DirectContentUnder;
float usedHeights = h;
while (usedHeights >= 0)
{
usedHeights -= cropHeight;
document.SetPageSize(new iTextSharp.text.Rectangle(1150f, cropHeight));
canvas.AddImage(image, w, 0, 0, h, 0, -usedHeights);
document.NewPage();
}
document.Close();
created = outputMemoryStream.ToArray();
outputMemoryStream.Write(created, 0, created.Length);
outputMemoryStream.Position = 0;
}
return created;
I also tried to set margin in the loop by document.SetMargins() - but that's not working.
You are mixing different things.
When you create margins, be it while constructing the Document instance or by using the setMargins() method, you create margins for when you let iText(Sharp) decide on the layout. That is: the margins will be respected when you do something like document.Add(image).
However, you do not allow iText to create the layout. You create a PdfContentByte named canvas and you decide to add the image to that canvas using a transformation matrix. This means that you will calculate the a, b, c, d, e, and f value needed for the AddImage() method.
You are supposed to do that Math. If you want to see a margin, then the values w, 0, 0, h, 0, and -usedHeights are wrong, and you shouldn't blame iTextSharp, you should blame your lack of insight in analytical geometrics (that's the stuff you learn in high school at the age of 16).
This might be easier for you:
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageByte);
float w = image.ScaledWidth;
float h = image.ScaledHeight;
// For the sake of simplicity, I don't crop the image, I just add 20 user units
iTextSharp.text.Rectangle page = new iTextSharp.text.Rectangle(w + 20, h + 20);
iTextSharp.text.Document document = new iTextSharp.text.Document(page);
PdfWriter writer = PdfWriter.GetInstance(document, outputMemoryStream);
// Please drop the line that prevents closing the output stream!
// Why are so many people making this mistake?
// Who told you you shouldn't close the output stream???
document.Open();
// We define an absolute position for the image
// it will leave a margin of 10 to the left and to the bottom
// as we created a page that is 20 user units to wide and to high,
// we will also have a margin of 10 to the right and to the top
img.SetAbsolutePosition(10, 10);
document.Add(Image);
document.Close();
Note that SetAbsolutePosition() also lets you take control, regardless of the margins, as an alternative, you could use:
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageByte);
float w = image.ScaledWidth;
float h = image.ScaledHeight;
// For the sake of simplicity, I don't crop the image, I just add 20 user units
iTextSharp.text.Rectangle page = new iTextSharp.text.Rectangle(w + 20, h + 20);
iTextSharp.text.Document document = new iTextSharp.text.Document(page, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(document, outputMemoryStream);
// Please drop the line that prevents closing the output stream!
// Why are so many people making this mistake?
// Who told you you shouldn't close the output stream???
document.Open();
// We add the image to the document, and we let iTextSharp decide where to put it
// As there is just sufficient space to fit the image inside the page, it should fit,
// But be aware of the existence of a leading; that could create side-effects
// such as forwarding the image to the next page because it doesn't fit vertically
document.Add(Image);
document.Close();

How to change text height in pdfbox

PDFBOX / JSF
Im trying to change the font height of a given text. I know how to change the fontsize only.
PDPageContentStream contentStreambc = new PDPageContentStream(doc1, page, true, true);
contentStreambc.setFont( fonta, 16 );
contentStreambc.beginText();
contentStreambc.moveTextPositionByAmount(200, 320);
contentStreambc.drawString( "abcdef");
contentStreambc.endText();
contentStreambc.close();
The code works fine. But How I change the font height ?
thanks in advance stack members.
If you need something like this
you can create it with this code:
PDRectangle rec = new PDRectangle(220, 70);
PDDocument document = null;
document = new PDDocument();
PDPage page = new PDPage(rec);
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document, page, true, true);
content.beginText();
content.moveTextPositionByAmount(7, 55);
content.setFont(PDType1Font.HELVETICA, 12);
content.drawString("Normal text (size 12)");
content.setTextMatrix(1, 0, 0, 1.5f, 7, 30);
content.drawString("Stretched text (size 12, factor 1.5)");
content.setTextMatrix(1, 0, 0, 2f, 7, 5);
content.drawString("Stretched text (size 12, factor 2)");
content.endText();
content.close();
document.save("SimplePdfStretchedText.pdf");
The code stretches the text by setting the text matrix accordingly; for details cf. chapter 9 of the PDF specification ISO 32000-1.
PS: As you mention bar codes in a comment to another answer, this should indeed allow you to make higher bar codes while keeping the distances.

Can't set custom font for pdf for PdfContentByte - DroidText/iText library

I'm trying to use a custom font, I don't get any error but it doesn't take it into account.
Rectangle pageSize = basePdf.getPageSize(i);
PdfContentByte pdfContentByte = stamper.getOverContent(i);
// Use custom font
if (!FontFactory.isRegistered(FUTURA_LIGHT)) {
FileHelper.copyFileFromAssetsToInternalStorage(mContext, FONT_PATH_IN_ASSETS);
FontFactory.register(mContext.getFilesDir() + "/" + FONT_PATH_IN_ASSETS, FUTURA_LIGHT);
}
Font myFont = FontFactory.getFont(FUTURA_LIGHT);
BaseFont font = myFont.getBaseFont();
pdfContentByte.saveState();
pdfContentByte.stroke();
pdfContentByte.restoreState();
// Start to add text
pdfContentByte.beginText();
pdfContentByte.setFontAndSize(font, 6);
if (fontColor != null) {
pdfContentByte.setColorFill(fontColor);
}
pdfContentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, message, pageSize.getWidth() / 2, 40, 0);
pdfContentByte.endText();
I've checked and the font is indeed registered, it just doesn't apply it to the PDF.
I found it by accident, I was trying to display accents by adding BaseFont.IDENTITY_H
here's the line that I changed:
Font myFont = FontFactory.getFont(FUTURA_LIGHT, BaseFont.IDENTITY_H);
Same problem.
because using Thai font.
My resolve to below,
String FONT_DEFAULT = ROOT_PATH + "/assets/THSarabunNew/THSarabunNew.ttf";
PdfContentByte pdfContentByte = pdfStamper.getOverContent(1);
pdfContentByte.beginText();
pdfContentByte.setFontAndSize(
BaseFont.createFont(
FONT_DEFAULT,
BaseFont.IDENTITY_H,
BaseFont.EMBEDDED
), 12);
pdfContentByte.setTextMatrix(50, 760); // set x and y co-ordinates
pdfContentByte.showText("สวัสดีครับ"); // add the text
pdfContentByte.endText();
Work for me.
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>

PDF Watermark for printing only, programmatically

I can watermark any PDF already, and the images inside, everything ok, but now I need the watermark only showing up when the PDF is printed... Is this possible? How?
I need to do this programmatically of course.
For future readers, this is possible to do by wrapping the watermark in a PDF layer (Optional Content Group), then configuring the Usage attribute of this layer as Print-Only. See the PDF Reference Document, Chapter 4-Graphics, part 4.10-Optional Content for more details.
Specifically, using itextsharp, I was able to get it working with the following, specifically - pdf version 1.7, and SetPrint("Watermark",true)
string oldfile = #"c:\temp\oldfile.pdf";
string newFile = #"c:\temp\newfile.pdf";
PdfReader pdfReaderS = new PdfReader(oldfile);
Document document = new Document(pdfReaderS.GetPageSizeWithRotation(1));
PdfWriter pdfWriterD = PdfWriter.GetInstance(document, new FileStream(newFile, FileMode.Create, FileAccess.Write));
pdfWriterD.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
document.Open();
PdfContentByte pdfContentByteD = pdfWriterD.DirectContent;
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
int n = pdfReaderS.NumberOfPages;
string text = "UNCONTROLLED";
for (int i = 1; i <= n; i++)
{
iTextSharp.text.Rectangle pageSizeS = pdfReaderS.GetPageSizeWithRotation(i);
float pageWidth = pageSizeS.Width / 2;
float pageheight = pageSizeS.Height / 2;
document.SetPageSize(pageSizeS);
document.NewPage();
PdfImportedPage pdfImportedPage = pdfWriterD.GetImportedPage(pdfReaderS, i);
PdfLayer layer1 = new PdfLayer("Watermark", pdfWriterD);
layer1.SetPrint("Watermark", true);
layer1.View = false;
layer1.On = false;
layer1.OnPanel = false;
pdfContentByteD.BeginLayer(layer1);
pdfContentByteD.SetColorFill(BaseColor.RED);
pdfContentByteD.SetFontAndSize(bf, 30);
ColumnText.ShowTextAligned(pdfContentByteD, Element.ALIGN_CENTER, new Phrase(text), 300, 700, 0);
pdfContentByteD.EndLayer();
pdfContentByteD.AddTemplate(pdfImportedPage, 0, 0);//, 0, 1, 0, 0);
}
document.Close();
pdfReaderS.Close();
You should probably make use of the fact that the screen uses RGB and the printer CMYK. You should be able to create two colors in CMYK that map to the same RGB value. This is of course not enough against a determined specialist.
The bOnScreen parameter determines whether the watermark will be displayed when the PDF is viewed on the computer screen, and bOnPrint determines whether it will be displayed when the PDF is printed.
-- https://acrobatusers.com/tutorials/watermarking-a-pdf-with-javascript