itext,xmlworker , Center a table horizontally with iText's XMLWorker

Center a table horizontally with iText's XMLWorker


Tag: itext,xmlworker

I've tried centering a table in two ways:

Attempt 1 code:

<h1>Attempt 1</h1>

<table style="width: 50%; margin: 0 auto;">

Attempt 2 code:

<h1>Attempt 2</h1>

<table style="width: 50%;" align="center">

Using the XMLWorker demo:

This is the HTML preview:

html preview

As you can see, both tables are centered.
Although, when I click "transform", I get this:

generated pdf

I also tried later wrapping the table in a <div style="text-align: center"></div> which didn't work


As explained in the comment section, this isn't supported yet in XML Worker. We'll add it to the next release. If you can't wait until the next release, please apply this patch:

diff --git a/src/main/java/com/itextpdf/tool/xml/html/table/ b/src/main/java/com/itextpdf/tool/xml/html/table/
index 541818bfc9..e262b4a406 100644
--- a/src/main/java/com/itextpdf/tool/xml/html/table/
+++ b/src/main/java/com/itextpdf/tool/xml/html/table/
@@ -165,6 +165,19 @@ public class Table extends AbstractTagProcessor {
             table.setHeaderRows(headerRows + footerRows);

+            if ( tag.getAttributes().containsKey(HTML.Attribute.ALIGN)) {
+                String value = tag.getAttributes().get(HTML.Attribute.ALIGN);
+                if ( value != null ) {
+                    if (value.equalsIgnoreCase(CSS.Value.RIGHT)) {
+                        table.setHorizontalAlignment(Element.ALIGN_RIGHT);
+                    } else if ( value.equalsIgnoreCase(CSS.Value.LEFT)) {
+                        table.setHorizontalAlignment(Element.ALIGN_LEFT);
+                    } else if ( value.equalsIgnoreCase(CSS.Value.CENTER)) {
+                        table.setHorizontalAlignment(Element.ALIGN_CENTER);
+                    }
+                }
+            }
             int direction = getRunDirection(tag);
             if (direction != PdfWriter.RUN_DIRECTION_DEFAULT) {


Arabic characters from html content to pdf using iText

I am having trouble to display the Arabic Characters from HTML Content in PDF Generation as "?" I am able to display the Arabic text from String variable. At the same time I am not able to generate the Arabic Text from the HTML String. I want to display the...

error while creating PDF

I am trying to generate a PDF using Android Studio. I am using the iText library, but when I add it into Android studio, I get the following error: Error:Execution failed for task ':app:dexDebug'. org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2 When I remove the...

How to extract text by a selected area from a PDF file using iText?

I am working on a program that extract texts from a PDF file in a specific area, I am using java and iText library. Right now, i can extract data by taping the area coordinations using this code: import; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.FilteredTextRenderListener; import com.itextpdf.text.pdf.parser.LocationTextExtractionStrategy; import com.itextpdf.text.pdf.parser.PdfTextExtractor;...

How to reorder the pages of a PDF file?

I am generating Table of Contents at last,I want to move Table of Contents at Beginning. Suppose that I have 16 pages in my PDF and that the TOC starts from page 13 and ends on page 15. I want to move the TOC to the second page, so that...

iTextSharp 5.5.6 PdfCopy Failing with “Cannot access a closed file”

This seems to be similar to this question: Merging Tagged PDF without ruining the tags I'm using the latest iTextSharp NuGet package (v5.5.6) trying to merge two tagged PDFs. When calling Document.Close() I'm getting an ObjectDisposedException originating from PdfCopy.FlushIndirectObjects(). at System.IO.__Error.FileNotOpen() at System.IO.FileStream.get_Position() at position, Byte[] bytes, Int32 off,...

Why is my PDF being generated as blank?

I am using ItextSharp and c#, MVC to generate a PDF report. However, when I generate the report the PDF comes back as blank (apart from a header which is working fine). I would love your input. The code that generates the report is as follows: using (var writer...

iText to remove Protected View from a PDF

I'm working on removing Protected View from a series of PDFs, and am trying to use the iText library within VBA. My main issue at this point is that I have no idea what method to use, and the iText documentation is pretty dense. I'm also feeling my way forward...

Can't set RTL direction for Hebrew letters while converting from *.xhtml to *.pdf by using iText library

I'm trying to convert *.xhtml with Hebrew characters (UTF-8) to PDF by using iText library but I getting all letter in reverse order. As far I understand from this question I can set RTL only for ColumnText and PdfCell objects: Arabic (and Hebrew) can only be rendered correctly in the...

Obtaining the hash/digest from a PCKS7 signed PDF file with iText

I'm writing a Java web service that signs PDF documents with iText from some clients in the network. Documents are being signed correctly, and can be verified with external tools. However, due to some legal restrictions in order to store this document in an official documentary repository I have to...

Converting images to PDF with iTextSharp preserve clipping path

We're looking to convert images in bulk to PDF, programmatically. So far it looks like we will be using iTextSharp but we have an issue with JPG images with clipping path. We are using the following code in our tests: using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None)) {...

Signing PDF - memory consumption

I tried some utilities for digital PDF signing based on iText v1 or v2 and found out that it seems whole PDF is loaded into memory (for 60M PDF process can take up to 300-400MB of memory). Can recent iText versions sign PDF without load it into memory? Updates I...

How to write bulleted list in pdf using itext jar but item should not in next line

Below is the code I have searched from net. this code is printing the each list item in next line but I don't want like that. Below is expected output I want to write in pdf: List orderedList = new List(List.ORDERED); orderedList.add(new ListItem("Item 1")); orderedList.add(new ListItem("Item 2")); orderedList.add(new ListItem("Item 3"));...

Textfield data is getting too small, when we enter more data into the textbox

If I apply, text.setOptions(TextField.MULTILINE | TextField.REQUIRED); to my text field, then I can enter more data, but the problem is the data is getting too small, then it becomes scrollable. Can we get a scrollbar instead, before it gets too small?...

Itext rectangle from milimeters

I try draw a A5 rentangle in a PDF with Itext using Rectangle class and Utilities.milimetersToPoints method but when i print the PDF and measure the rectangle the measurments is not the A5 dimensions. public static boolean createPDF(String pathPDF) { Document document = new Document(PageSize.A4); try { PdfWriter writer =...

Itext std deviation symbol σ not printing

Using itext to generate PDFs and I have a symbol σ which does not print in the pdf. Is this because of font selection (using HELVETICA_BOLD)? Can anyone help

How to flatten pdf with Itext in c#?

I need to remove all form fields of a pdf, so I am using iText and try to flatten the pdf. Because of legacy code I am restricted to iText version My Code is: public static byte[] RemoveAcroFields(String filename) { if (filename != null && File.Exists(filename)) { byte[] pdfFile...

iText, FileNotFoundException when adding image to pdf

I am trying to add an image to my pdf using iText and when following the iTexts documentation on this its just simply telling me to do this: Image img = Image.getInstance("res/drawable/toplogos.png"); document.add(img); But I am getting FileNotFoundException. Why is that? The file is in the drawable folder. Thanks....

Where is the Origin (x,y) of a PDF page?

I am using iText to create my PDF files. I want to position text at some specific place in the document using the method I found here. However, I cannot figure out where to find the origin of the coordinate system of the page. bottom left corner?,top right corner?bottom right...

How to change the spacing between words and characters?

I want to set the text alignment to justified, but I don't want iText to add any extra space between the characters (see figure 1). I prefer space between words as shown in figure 2. With this code, I get the result shown in figure 1. public static void main(String[]...

Control 'testGridview' of type 'SPGridView' must be placed inside a form tag with runat=server

I have a spgridview and want to export its content to pdf. I am using itextsharp for the same. But error is encountered at rendercontrol call. I have already tried the solutions mentioned in the below thread. Question Also I have tried using public override void VerifyRenderingInServerForm(Control control) { return;...

Register font from byte array in iText

Is it possible to register a font from a byte array, instead of using file paths? The FontFactory class has two methods for registering fonts. Both use file/folder paths to register fonts: Register RegisterDirectory I looked into the iText source for clues, but I don't understand how the font files...

Generate pdf file dynamically from html template and produce table of contents in java

We have an editor, which is used to design templates for catalogs,it is basically for designing purpose, first we design a template in the editor and bind our data in that template format. we get the template in HTML format from front end. From that template i need to bind...

iText Stamping - Java [duplicate]

This question already has an answer here: how to add blank page in digitally signed pdf using java? 2 answers I am having trouble with stamping PDF documents without invalidating digital signatures. Current, I succeeded stamping a PDF. However, if the document is previously signed the signature is no...

How to convert pdf into text file using itext liberary

Below is my code for converting a pdf file into a text file. The code successfully runs, but it doesn't generate the resulting text file (Sample.txt). Can anyone shed some light on this? The code is partly based on an example of the first iText in action book... import com.lowagie.text.*;...

iTextPDF hyperlink not linking to the right place

I have a bunch of PDF's which I have merged by this point in the code. At the beginning of the merged PDF I have a contents page which links to said PDF's respectively. These pdfAction.gotoLocalPage links sometimes don't work correctly and instead jump to between the bottom of the...

Alignment issue with multiline text form fields in iTextSharp

I have written an application to programatically fill out a form in a PDF template from a database and save the result to disk. Everything is working correctly apart from any multi-line text fields which are not rendering as expected. They should be top, left aligned with no gaps between...

Save JavaFX ScrollPane content to PDF file

I'm using the below code to save the content of a ScrollPane in my JavaFx Application to a PDF file. button.setOnMouseClicked(new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { File pdfFile = fileChooser.showSaveDialog(primaryStage); try { BufferedImage bufImage = SwingFXUtils.fromFXImage(scrollPane.snapshot(new SnapshotParameters(), null), null); FileOutputStream out = new FileOutputStream(new File("../temp.jpg")); javax.imageio.ImageIO.write(bufImage, "jpg", out);...

Sign concatenated PDF in append mode with CERTIFIED_NO_CHANGES_ALLOWED

I tried to sign PDF with append mode and certification level CERTIFIED_NO_CHANGES_ALLOWED but certain PDF files shown as modified and therefore invalid in Acrobat. itext 5.5.6, code: PdfStamper stp = PdfStamper.createSignature(reader, os,'\0',null,true); PdfSignatureAppearance app = stp.getSignatureAppearance(); app.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); PDf file is created with wkhtmltopdf and concatenated with itself with pdfunite (CentOS...

Error in PDF Export

Here is my code snippet- getResponse().setContentType(NAPSConstants.PDF_CONTENT_TYPE); getResponse().setHeader(NAPSConstants.PDF_CONTENT_DISP, NAPSConstants.PDF_ATTACHMENT_FILE+getText("rcmid.details")+NAPSConstants.PDF_EXTN); //Set the Page Size Document document = new Document(PageSize.A3, 40, 40, 40, 40); PdfPTable table = new PdfPTable(rcmDetailsCols.length); for(RCMIDPartsDetailsDTO part : rcmidDTO.getPartsDetailsDTO()){ table.addCell(part.getPartStatus().equals(NAPSConstants.Active) ? PDFHelper.dataCell(...

link coming twice while exporting to pdf using itextsharp

my asp boundfield: <asp:BoundField DataField = "SiteUrl" HtmlEncode="false" HeaderText = "Team Site URL" SortExpression = "SiteUrl" ></asp:BoundField> My itextsharpcode for (int i = 0; i < dtUIExport.Rows.Count; i++) { for (int j = 0; j < dtUIExport.Columns.Count; j++) { if (j == 1) { continue; } string cellText = Server.HtmlDecode(dtUIExport.Rows[i][j].ToString());...

Multiple signatures with Itext - issue with existing signature blocks

So im currently working on a project to sign PDF documents and I ran into a problem. So i can sign documents correctly without any problems if I specify the block to sign i.e. signatureAppearance.setVisibleSignature(rectangle, page, signingBlockName); I can add multiple signatures without a problem and all of the signatures...

I have a pdf from which I have to extract data and show but I am getting this exception, I'm not being able to figure out what is this Exception is?

I have this pdf file to extract data from, but the problem is when I'm running this piece of code as a simple java program, it works like a charm but when I tried this code on JSP servlet it gave out this exception and I'm not being able to...

Itext get special letters from pdf

I am trying to extract accented words from pdf e book . The best results are produced when using itext library , but I fail to get accents from words . example : побеђивање -should come out as- побеђи́ва̄ње (accents are missing) The letters are Cyrillic Serbian . I tried...

How to add border to paragraph in itext pdf library in java?

I have created a paragraph in using itext pdf library in java. I have to add border to paragraph, not to the whole document. How to do it ?

Using iText to save pdf to ColdFusion Variable

I need to use iText with ColdFusion (CF) because CFDocument won't do everything I need it to, however I would like to return the result into a CF Variable instead of saving it to a file. It seems that every example out there saves the results to a file. I'm...

Align content in PDF using itext in java

I am stuck up with this problem for sometime now. I'm drawing a pie chart to the document and displaying the jtable data. I am not able to align the contents in the pdf file. How do I align the jtable data as well as the pie chart to this...

How can I write all the pages in the text document

I am trying to write extracted text of the pdf file into text document but currently, only the first page is being written in the text document although 6 pages are being output in the console of eclipse. How can I fix that? I appreciate any help. try { PdfReader...

Merge documents to create TOC in iText (Java)

When creating documents with iText that need a table of contents, I have usually used a process where I create the main document in memory, create the TOC as a separate document in memory (using dummy links), merge them as a third document, and then use a PdfStamper to reconcile...

iText -PDF reading issue on heading levels ( h1 - h6 )

Generated PDF by iText-XMLWorker 5.5.4. Everything is reading perfectly except heading levels (h1-h6) in screen reader. Below code works fine on browsers but not in PDF. <section> <h1>heading 1</h1> <h2>heading 2 </h2> <h3>heading 3 </h3> <h4>heading 4 </h4> </section> ...

2D barcode generation issue in Java

I am generating barcodes using iText API, everything looks good when it is linear barcodes when it is 2D barcodes then barcodes are placed into pdf document as images, hence reducing the quality of the barcode on low resolution printers and unable to scan the barcode. Below is the code...

PDF generated by iText -> text missing after saving PDF to local drive

I am producing a PDF file in a HttpServlet with itText. Adding a Text on the canvas. If I open the url the PDF is shown correctly with the text. Also if I print it direclty from the browser, the text is visible on the printed paper. If I download...

Extracting an embedded object from a pdf

I had embedded a byte array into a pdf file (Java). Now I am trying to extract that same array. The array was embedded as a "MOVIE" file. I couldn't find any clue on how to do that... Any ideas? Thanks! EDIT I used this code to embed the byte...

Ordered and Unordered List is not rendered during the PDF Generation

I am using iText-5.5.6 and XMLWorker-5.5.6. I am having strange issue during the PDF Generation where as I am not able to see the Ordered or Unordered list from the source HTML Content. I am getting the HTML Content from the Editor Control. And the content is like the below:...

Viewing PDF with Java [duplicate]

This question already has an answer here: Java PDF Viewer 2 answers I am working on a program that should create, Show and Extract text from PDF files but i cant find a free library that will show PDF files or at least convert them to images to work...

Making editable cells of a table readonly having Scroll Bar with itext

Please find the below code. public class MakingFieldReadOnly implements PdfPCellEvent { /** The resulting PDF. */ public static final String RESULT1 = "text_fields.pdf"; /** The resulting PDF. */ public static final String RESULT2 = "text_filled.pdf"; /** The text field index of a TextField that needs to be added to a...

iTextPdf-How to add a FormField to Section without Position?

In want to add interactive from fields like check boxes to a new created multiple page pdf, in the example from itext the code looks like this: PdfContentByte canvas = writer.getDirectContent(); Rectangle rect = new Rectangle(180, 806 * 40, 200, 788 * 40); RadioCheckField checkbox = new RadioCheckField(writer, rect, "box1",...

Center a table horizontally with iText's XMLWorker

I've tried centering a table in two ways: Attempt 1 code: <h1>Attempt 1</h1> <table style="width: 50%; margin: 0 auto;"> <tr> <th>foo</th> <td>bar</td> </tr> <tr> <th>foo</th> <td>bar</td> </tr> </table> Attempt 2 code: <h1>Attempt 2</h1> <table style="width: 50%;" align="center"> <tr> <th>foo</th> <td>bar</td> </tr> <tr> <th>foo</th> <td>bar</td> </tr>...