Set table using "setFixedPosition" on specified page in a reopened PDF document - itext

This question is the follow up to another question on stackoverflow.
I open an existing PDF with this code snippet:
reader = New PdfReader(filenameSource)
writer = New PdfWriter(destFile)
pdf = New PdfDocument(reader, writer)
doc = New Document(pdf, pdf.GetDefaultPageSize, False)
I can add a paragraph now via doc.add(new Paragraph(...))
But when I try to place a table with table.setFixedPosition(...), the table doesn´t show on the page.
Has anybody any hint for me?
Thanks and best regards
Benjamin

Based on your information I wrote this piece of code:
PdfReader reader = new PdfReader("LoremIpsum.pdf");
PdfWriter writer = new PdfWriter("LoremIpsum-with-positioned-table.pdf");
PdfDocument pdf = new PdfDocument(reader, writer);
Document doc = new Document(pdf, pdf.GetDefaultPageSize(), false);
Table table = new Table(new float[] { 200 });
table.AddCell(new Cell().Add(new Paragraph("test")).SetBackgroundColor(ColorConstants.CYAN));
table.SetFixedPosition(1, 100, 100, 200);
doc.Add(table);
doc.Close();
This didn't reproduce your issue
when I try to place a table with table.setFixedPosition(...), the table doesn´t show on the page.
because the result looks like this:
The table clearly shows.

Related

Create Muti Page PDF Document from One Page Document

I'm using iText7 for .NET c#. I'm trying to create a multi page PDF document (n-number of pages) in memory where the source pdf document consists of only one page.
I can create a new document with the one page, but unable to create the additional pages as needed. I've tried
MemoryStream ms = new MemoryStream();
Stream s1 = Assembly.GetExecutingAssembly().GetManifestResourceStream("doc.pdf");
s1.CopyTo(ms)
PdfReader readerSrc = new PdfReader(ms);
PdfDocument srcPdfDoc = new PdfDocument(readerSrc);
MemoryStream msDest = new ByteArrayOutputStream();
PdfDocument destPdfDoc - new PdfDocument(new PdfWriter(msDest));
srcPdfDoc.CopyPageTo(1,1,destPdfDoc)
destPdfDoc.AddNewPage(1, new PageSize.A4)
srcPdfDoc.CopyPageTo(1,2,destPdfDoc)
But then I get an ArgumentOutOfRange exception...Index out of range...etc....
I've tried closing the destPdfDoc to then re-open it thinking that the second page hadn't been written until I close it. But then when open the destPdfDoc up the 2nd time, it has no pages. I can't figure out how to open up the destPdfDoc in like "Append" mode. If that makes sense. Bottom line, I'm lost.
I've done this using iTextSharp, but then when using the new iText7, the library changed and my old code doesn't work anymore.
I figured it out.
MemoryStream ms = new MemoryStream();
Stream s1 = Assembly.GetExecutingAssembly().GetManifestResourceStream("doc.pdf");
s1.CopyTo(ms)
PdfReader readerSrc = new PdfReader(ms);
PdfDocument srcPdfDoc = new PdfDocument(readerSrc);
MemoryStream msDest = new ByteArrayOutputStream();
PdfDocument destPdfDoc - new PdfDocument(new PdfWriter(msDest));
PdfMerger merger = new PdfMeger(destPdfDoc);
merger.Merge(srcPdfDoc , 1,1)
merger.Merge(srcPdfDoc , 1,1)
destPdfDoc.Close();
srcPdfDoc.Close();

How does the itext document divides its pages and fits elements into a page

Hi I recently posted a question here :
IText PDFImage seems to shrink or disappear during new pages after upgrade from 2.1.7 to 5.5.5 (Java .jars)
But I think it is not the problem with the library but more of a missing setting sort of problem. I am wondering if there is a way to control what element gets drawn on the existing page verses pushing to a new page
I want to do the following
-create document
-create pdfPTable
-create a bunch of image element for each PdfPCells
-add to pdfPTable then write to document
Result: It seems that some images get shrink near the end/beginng of the page or is missing ( seems like its trying to fit on to the page )
Sample code again for visibility
ByteArrayOutputStream baos = createTemporaryOutputStream();
Document doc = newDocument();
PdfWriter writer = newWriter(doc, baos);
writer.setViewerPreferences(PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage);
//create page rectangle landscape
Rectangle page = new Rectangle(PageSize.A4.rotate());
doc.setPageSize(page);
doc.setMargins((float)36.0, (float)36.0, (float)36.0, (float)36.0);
doc.open();
//create element pdf table.
PdfPTable table = new PdfPTable(new float[]{(float) 770.0});
table.setWidthPercentage(100);
table.setSplitRows(true);
table.setSplitLate(false);
table.setHeaderRows(0);
// in my case I used 5 800*600 images (same picture)
//then I loop through them and create pdfcell
//and then add it to table which then gets added to the document
List<Image> hi = (List<Image>) model.get("images");
for (Image image : hi) {
com.itextpdf.text.Image pdfImage = com.itextpdf.text.Image.getInstance(image.getBytes());
pdfImage.scalePercent((float) (0.8642384 * 100));
PdfPCell cell = new PdfPCell(pdfImage, false);
table.addCell(cell);
}
doc.add(table);
doc.close();
thank you for your time. Any insight as to what my problem is would be helpful

Html to PDF , text inside <pre> not coming good in PDF

I am trying to convert html to pdf with iText API(itextpdf.5.5.7.jar, xmlworker 5.5.7.jar), everything is good except the text inside the pre tag.
In html the text inside the pre is good but in PDF the formatting is totally gone and simply coming in normal lines without formatting. I checked the blogs but I did not find correct answer.
Please find the screen shots for HTML and PDF.
HTML screen:
PDF screen:
this is my code
String pdfFileName="C:\test.pdf";
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(pdfFileName));
writer.setInitialLeading(12.5f);
document.open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
CSSResolver cssResolver = XMLWorkerHelper.getInstance()
.getDefaultCssResolver(true);
Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
new HtmlPipeline(htmlContext, new PdfWriterPipeline(document,
writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser p = new XMLParser(worker);
File input = new File(completeHtmlFilePath);
p.parse(new InputStreamReader(new FileInputStream(input), "UTF-8"));
document.close();
return pdfFileNameWithPath;

adding pushbutton to already existing templates [duplicate]

I have used iText to fill data into existing AcroForm fields in a PDF.
I am now looking for a solution to add new AcroForm fields to a PDF. Is this possible with iText? If so, how can I do this?
This is documented in the official documentation, more specifically in the SubmitForm example. When using a tool such as iText, you should read the official documentation first ;-)
Anyway, I've written you a simple example called AddField. It adds a button field at a specific position defined by new Rectangle(36, 700, 72, 730).
public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PushbuttonField button = new PushbuttonField(
stamper.getWriter(), new Rectangle(36, 700, 72, 730), "post");
button.setText("POST");
button.setBackgroundColor(new GrayColor(0.7f));
button.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
PdfFormField submit = button.getField();
submit.setAction(PdfAction.createSubmitForm(
"http://itextpdf.com:8180/book/request", null,
PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES));
stamper.addAnnotation(submit, 1);
stamper.close();
}
}
As you can see, you need to create a PdfFormField object (using helper classes such as PushbuttonField, TextField,...) and then use PdfStamper's addAnnotation() method to add the field to a specific page.

How to add a form field to an existing pdf with itextsharp?

How to add a form field to an existing pdf with itextsharp?
I have an existing pdf document, I'd like to add form fields to it without creating a copy and writing out a new document.
After further review, the ruling on the field is overturned. Turns out if you form flatten the stamper the fields do not show on the resulting document (because they lack 'appearance' settings). BTW, form flattening prevents further edits of a form field. Now we can add appearance to the form, however, an easier way is to use the TextField class and not worry about explicitly setting up 'appearance' objects.
public void ABetterWayToAddFormFieldToExistingPDF( )
{
PdfReader reader = new PdfReader(#"c:\existing.pdf");
FileStream out = new FileStream(#"C:\existingPlusFields.pdf", FileMode.Create, FileAccess.Write);
PdfStamper stamp = new PdfStamper(reader, out);
TextField field = new TextField(stamp.Writer, new iTextSharp.text.Rectangle(40, 500, 360, 530), "some_text");
// add the field here, the second param is the page you want it on
stamp.AddAnnotation(field.GetTextField(), 1);
stamp.FormFlattening = true; // lock fields and prevent further edits.
stamp.Close();
}
I struggled with this for awhile so figured I'd post the Question & Answer
Using the PdfStamper itext class is the key. (I guess this does make a copy but it's much cleaner than using the itext PdfCopy classes).
public void AddFormFieldToExistingPDF( )
{
PdfReader reader = new PdfReader(#"c:\existing.pdf");
FileStream out = new FileStream(#"C:\existingPlusFields.pdf", FileMode.Create, FileAccess.Write);
PdfStamper stamp = new PdfStamper(reader, out);
PdfFormField field = PdfFormField.CreateTextField(stamp.Writer, false, false, 50);
// set a field w/some position and size
field.SetWidget(new iTextSharp.text.Rectangle(40, 500, 360, 530),
PdfAnnotation.HIGHLIGHT_INVERT);
field.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
field.FieldName = "some_field";
// add the field here, the second param is the page you want it on
stamp.AddAnnotation(field, 1);
stamp.Close();
}
Using pdfStamper you can complete it.
PdfStamper Stamper= new PdfStamper(new PdfReader(sourcefile), File.Create(NewOutputFile));
TextField moreText = new TextField(Stamper.Writer,
new iTextSharp.text.Rectangle(20, 20, 590, 780), "moreText");
moreText.Visibility = TextField.VISIBLE_BUT_DOES_NOT_PRINT;
moreText.Text = "Use this space for any additional information";
moreText.Options = (TextField.MULTILINE);
PdfFormField Fieldtxt = moreText.GetTextField();
Stamper.AddAnnotation(Fieldtxt, n);