I'm working with a label printer which prints my pdf file. I create the file like this:
public static Document createPDF() {
float pageWidth = 176f;
float pageHeight = 200f;
Rectangle pageSize = new Rectangle(pageWidth, pageHeight);
Document document = new Document(pageSize);
document.setMargins(5, 5, 1, 0);
String file = MainActivity.FILE_URI;
try {
PdfWriter.getInstance(document,new FileOutputStream(file));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (DocumentException e1) {
e1.printStackTrace();
}
return document;
}
Then I add some paragraphs to it. The paragraphs have variabel length. When I exceed the length of the page IText adds another page. The pages are 62 x 75 mm.
I want to change the length based on the amount of text so I don't waste paper. I tried this:
try {
PdfReader reader = new PdfReader(MainActivity.FILE_URI);
while (reader.getNumberOfPages() > 1) {
float pageHeight = document.getPageSize().getHeight();
float pageWidth = document.getPageSize().getWidth();
pageHeight += 50f;
document.setPageSize(new Rectangle(pageWidth, pageHeight));
}
} catch (IOException e) {
e.printStackTrace();
}
But it's not working. The pages aren't getting longer so the number of pages stays the same and causes a loop.
Anyone knows a solution?
Essentially you need to first draw on a very long page, longer than any plausible input to your use case, and then cut off the lower, empty parts.
This means that you have to start by setting your pageHeight value accordingly. A safe value is
float pageHeight = 14400f;
The result you get now is a PDF document with one extremely long page, more than 5m in length.
This page has to be shortened to match the contents. This can be done in a second pass like this (I use the pageSize rectangle you have already defined; INTERMEDIATE points to the PDF you generated in the first pass):
PdfReader reader = new PdfReader(INTERMEDIATE);
PdfStamper stamper = new PdfStamper(reader, FINAL_RESULT);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
TextMarginFinder finder = parser.processContent(1, new TextMarginFinder());
PdfDictionary page = reader.getPageN(1);
page.put(PdfName.CROPBOX, new PdfArray(new float[]{pageSize.getLeft(), finder.getLly(), pageSize.getRight(), pageSize.getTop()}));
stamper.markUsed(page);
stamper.close();
reader.close();
Depending on your document data you can keep the intermediary PDF in memory by using a ByteArrayOutputStream for your PdfWriter, retrieving the intermdeiate PDF as byte[] after document.close(), and feeding that byte[] into the PdfReader in the second step.
Related
I am using PDFBox to join two PDFs side by side.
I am using the following code:
PDDocument outDoc = new PDDocument();
int maxPages = targetDoc.getNumberOfPages();
if (sourceDoc.getNumberOfPages() > targetDoc.getNumberOfPages()) {
maxPages = sourceDoc.getNumberOfPages();
}
PDPage sourceIndexPage;
PDPage targetIndexPage;
PDRectangle pdf1Frame;
PDRectangle pdf2Frame;
PDRectangle outPdfFrame;
COSDictionary dict;
PDPage outPdfPage;
LayerUtility layerUtility;
PDFormXObject sourceFormPDF;
PDFormXObject targetFormPDF;
AffineTransform afLeft;
AffineTransform afRight;
for (int indexPage = 0; indexPage < maxPages; indexPage++) {
// Create output PDF frame
try {
sourceIndexPage = sourceDoc.getPage(indexPage);
} catch (IndexOutOfBoundsException error) {
sourceDoc.addPage(new PDPage());
sourceIndexPage = targetDoc.getPage(indexPage);
}
try {
targetIndexPage = targetDoc.getPage(indexPage);
} catch (IndexOutOfBoundsException error) {
targetDoc.addPage(new PDPage());
targetIndexPage = targetDoc.getPage(indexPage);
}
sourceIndexPage.setRotation(0);
targetIndexPage.setRotation(0);
pdf1Frame = sourceIndexPage.getCropBox();
pdf2Frame = targetIndexPage.getCropBox();
outPdfFrame = new PDRectangle(pdf1Frame.getWidth() + pdf2Frame.getWidth(),
Math.max(pdf1Frame.getHeight(), pdf2Frame.getHeight()));
// Create output page with calculated frame and add it to the document
dict = new COSDictionary();
dict.setItem(COSName.TYPE, COSName.PAGE);
dict.setItem(COSName.MEDIA_BOX, outPdfFrame);
dict.setItem(COSName.CROP_BOX, outPdfFrame);
dict.setItem(COSName.ART_BOX, outPdfFrame);
outPdfPage = new PDPage(dict);
outDoc.addPage(outPdfPage);
// Source PDF pages has to be imported as form XObjects to be able to insert them at a specific point in the output page
// pageNumber
layerUtility = new LayerUtility(outDoc);
sourceFormPDF = layerUtility.importPageAsForm(sourceDoc, indexPage);
targetFormPDF = layerUtility.importPageAsForm(targetDoc, indexPage);
// Add form objects to output page
afLeft = new AffineTransform();
layerUtility.appendFormAsLayer(outPdfPage, sourceFormPDF, afLeft, "left " + indexPage);
afRight = AffineTransform.getTranslateInstance(pdf1Frame.getWidth(), 0.0);
layerUtility.appendFormAsLayer(outPdfPage, targetFormPDF, afRight, "right" + indexPage);
}
outDoc.save("oudDoc.pdf");
The issue I have is that for some documents, the size of the outDoc is too high. I expected it to be something around dim source document + dim target document, but it is 10x, 20x more in reality.
Looking inside the document's structure, I noticed that I am repeating common resources that in the original PDFs were separated. Is there a way to compress/optimize my code to have less space on disk?
We solved the problem by postprocessing the generated pdf with ghostscript
I'm using itext5 to scale down pdf document, however i notice that the rotation information is rarely used in pdf documents metadata, it's still possible to find out the orientation by checking the width and the height of the page but with the following pdf document i end up with a pdf that has both pages in landscape orientation and in portrait orientation however all the pages are rendered in the same orientation (in the common pdf viewers).
My question is where is that information stored ? How the pdf viewer is able to render the document as it should ?
This the orignal pdf file
This is the metadata i'm able to retrieve
This is the method used :
Document document = new Document(MarginsPDFHelper.DIM_PAGE, MarginsPDFHelper.MARGIN_GEN, MarginsPDFHelper.MARGIN_GEN, MarginsPDFHelper.MARGIN_TOP, MarginsPDFHelper.MARGIN_BOT);
try {
PdfReader reader = new PdfReader(pdfByte);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte content = writer.getDirectContent();
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
document.newPage();
PdfImportedPage page = writer.getImportedPage(reader, i);
Rectangle pageSize = reader.getPageSizeWithRotation(i);
float scaleX = MarginsPDFHelper.DIM_PAGE.getWidth() / pageSize.getWidth();
float scaleY = MarginsPDFHelper.DIM_PAGE.getHeight() / pageSize.getHeight();
float scale = Math.min(scaleX, scaleY);
content.addTemplate(page, scale, 0, 0, scale, 0, 0);
}
return outputStream.toByteArray();
} catch (Exception e) {
LOGGER.error("Can not scale pdf", e);
} finally {
if (document.isOpen()) {
document.close();
} }
This the result i get after scaling down with itext5
i'm using iText 5.5.5 with Java5.
I'm trying to merge some PDF/A. when I got a "PdfAConformanceException: PDF array is out of bounds".
Trying to find error I find the "bad PDF" that cause the error and when I try to copy just it exception throw again. This error don't appear always, it appear just when this PDF/A is in the "job chain"; I tried with some other files and it's all fine. I cant share with you source PDF 'couse it's restricted.
That's my piece of code:
_log.info("Start Document Merge");
// Output pdf
ByteArrayOutputStream bos = new ByteArrayOutputStream();
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
PdfCopy copy = new PdfACopy(document, bos, PdfAConformanceLevel.PDF_A_1B);
PageStamp stamp = null;
PdfReader reader = null;
PdfContentByte content = null;
int outPdfPageCount = 0;
BaseFont baseFont = BaseFont.createFont("Arial", BaseFont.WINANSI, BaseFont.EMBEDDED);
copyOutputIntents(reader, copy);
// Loop over the pages in that document
try {
int numberOfPages = reader.getNumberOfPages();
for (int i = 1; i <= numberOfPages; i++) {
PdfImportedPage pagecontent = copy.getImportedPage(reader, i);
_log.debug("Handling page numbering [" + i + "]");
stamp = copy.createPageStamp(pagecontent);
content = stamp.getUnderContent();
content.beginText();
content.setFontAndSize(baseFont, Configuration.NumPagSize);
content.showTextAligned(PdfContentByte.ALIGN_CENTER, String.format("%s %s ", Configuration.NumPagPrefix, i), Configuration.NumPagX, Configuration.NumPagY, 0);
content.endText();
stamp.alterContents();
copy.addPage(pagecontent);
outPdfPageCount++;
if (outPdfPageCount > Configuration.MaxPages) {
_log.error("Pdf Page Count > MaxPages");
throw new PackageException(Constants.ERROR_104_TEXT, Constants.ERROR_104);
}
}
copy.freeReader(reader);
reader.close();
copy.createXmpMetadata();
document.close();
} catch (Exception e) {
_log.error("Error during mergin Document, skip");
_log.debug(MiscUtil.stackToString(e));
}
return bos.toByteArray();
That's the full stacktrace:
com.itextpdf.text.pdf.PdfAConformanceException: PDF array is out of bounds.
at com.itextpdf.text.pdf.internal.PdfA1Checker.checkPdfObject(PdfA1Checker.java:269)
at com.itextpdf.text.pdf.internal.PdfAChecker.checkPdfAConformance(PdfAChecker.java:208)
at com.itextpdf.text.pdf.internal.PdfAConformanceImp.checkPdfIsoConformance(PdfAConformanceImp.java:71)
at com.itextpdf.text.pdf.PdfWriter.checkPdfIsoConformance(PdfWriter.java:3480)
at com.itextpdf.text.pdf.PdfWriter.checkPdfIsoConformance(PdfWriter.java:3476)
at com.itextpdf.text.pdf.PdfArray.toPdf(PdfArray.java:165)
at com.itextpdf.text.pdf.PdfDictionary.toPdf(PdfDictionary.java:149)
at com.itextpdf.text.pdf.PdfArray.toPdf(PdfArray.java:175)
at com.itextpdf.text.pdf.PdfDictionary.toPdf(PdfDictionary.java:149)
at com.itextpdf.text.pdf.PdfIndirectObject.writeTo(PdfIndirectObject.java:158)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.write(PdfWriter.java:420)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:398)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:373)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:369)
at com.itextpdf.text.pdf.PdfWriter.addToBody(PdfWriter.java:843)
at com.itextpdf.text.pdf.PdfCopy.addToBody(PdfCopy.java:839)
at com.itextpdf.text.pdf.PdfCopy.addToBody(PdfCopy.java:821)
at com.itextpdf.text.pdf.PdfCopy.copyIndirect(PdfCopy.java:426)
at com.itextpdf.text.pdf.PdfCopy.copyIndirect(PdfCopy.java:446)
at com.itextpdf.text.pdf.PdfCopy.copyObject(PdfCopy.java:577)
at com.itextpdf.text.pdf.PdfCopy.copyDictionary(PdfCopy.java:503)
at com.itextpdf.text.pdf.PdfCopy.copyObject(PdfCopy.java:573)
at com.itextpdf.text.pdf.PdfCopy.copyDictionary(PdfCopy.java:503)
at com.itextpdf.text.pdf.PdfCopy.copyObject(PdfCopy.java:573)
at com.itextpdf.text.pdf.PdfCopy.copyDictionary(PdfCopy.java:493)
at com.itextpdf.text.pdf.PdfCopy.copyDictionary(PdfCopy.java:519)
at com.itextpdf.text.pdf.PdfCopy.addPage(PdfCopy.java:663)
at com.itextpdf.text.pdf.PdfACopy.addPage(PdfACopy.java:115)
at it.m2sc.engageone.documentpackage.generator.PackageGenerator.mergePDF(PackageGenerator.java:256)
In that specific case, the problem depends by a specific Font ( Gulim ) that is too big to be embedded in PDF/A-1 file. When that font was removed, everything war run fine.
Everything I have read regarding iText says you should be able to set the page size and then create a new page. But for some reason when I try this my first page isn't rotated. But my second is. Any ideas?
response.setContentType("application/pdf");
Document document = new Document();
try{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter.getInstance(document, buffer);
document.open();
//Start a new page
document.setPageSize(PageSize.LETTER.rotate()); // 11" x 8.5" new Rectangle(792f, 612f)
document.newPage();
Paragraph topText = new Paragraph();
// add some content here...
document.close();
DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
for(int i = 0; i < bytes.length; i++) {
dataOutput.writeByte(bytes[i]);
}
} catch (DocumentException e) {
e.printStackTrace();
}
document.newPage() really means "finish the current page and open a new one". This implies that after you open() a document, you already have a blank page (with whatever size the document had set before) ready.
You should set your page size before opening the document:
document.setPageSize(PageSize.LETTER.rotate());
document.open();
I'm using the iText library, and I'm trying to add a watermark at the bottom of the page. The watermark is simple, it has to be centered an has an image on the left and a text on the right.
At this point, I have the image AND the text in a png format. I can calculate the position where I want to put the image (centered) calculating the page size and image size, but now I want to include the text AS text (better legibility, etc.).
Can I embed the image and the text in some component and then calculate the position like I'm doing now? Another solutions or ideas?
Here is my actual code:
try {
PdfReader reader = new PdfReader("example.pdf");
int numPages = reader.getNumberOfPages();
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream("pdfWithWatermark.pdf"));
int i = 0;
Image watermark = Image.getInstance("watermark.png");
PdfContentByte addMark;
while (i < numPages) {
i++;
float x = reader.getPageSizeWithRotation(i).getWidth() - watermark.getWidth();
watermark.setAbsolutePosition(x/2, 15);
addMark = stamp.getUnderContent(i);
addMark.addImage(watermark);
}
stamp.close();
}
catch (Exception i1) {
logger.info("Exception adding watermark.");
i1.printStackTrace();
}
Thank you in advance!
you better check this:
import com.lowagie.text.*;
import java.io.*;
import com.lowagie.text.pdf.*;
import java.util.*;
class pdfWatermark
{
public static void main(String args[])
{
try
{
PdfReader reader = new PdfReader("text.pdf");
int n = reader.getNumberOfPages();
// Create a stamper that will copy the document to a new file
PdfStamper stamp = new PdfStamper(reader,
new FileOutputStream("text1.pdf"));
int i = 1;
PdfContentByte under;
PdfContentByte over;
Image img = Image.getInstance("watermark.jpg");
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.WINANSI, BaseFont.EMBEDDED);
img.setAbsolutePosition(200, 400);
while (i < n)
{
// Watermark under the existing page
under = stamp.getUnderContent(i);
under.addImage(img);
// Text over the existing page
over = stamp.getOverContent(i);
over.beginText();
over.setFontAndSize(bf, 18);
over.showText("page " + i);
over.endText();
i++;
}
stamp.close();
}
catch (Exception de)
{}
}
}
(source)
is a bit ugly but, can't you add the image and the text to a table and then center it?