### Hello World PDF creation in iText 5 Source: https://kb.itextpdf.com/it5kb/getting-started The canonical iText example showing the five steps to create a PDF from scratch: create a Document, get a PdfWriter instance, open the document, add a Paragraph, and close the document. This is the minimal setup for any iText PDF generation task. ```java // step 1 Document document = new Document(); // step 2 PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 document.add(new Paragraph("Hello World!")); // step 5 document.close(); ``` -------------------------------- ### Hello PDF! - Create a simple PDF with iText Source: https://kb.itextpdf.com/__attachments/a_93ff56ccde2c49903cce0250f8cf5b3bbbf414efc01f7966cb3a5fd0ef36eec1/README.pdf?cb=3f12a79fd3a5a3d964e8951433aca1cb Minimal Java example that creates a PDF file named hello-pdf.pdf in the current directory. Uses PdfWriter, PdfDocument, Document, and Paragraph. The try-with-resources block automatically closes the document. Requires the iText Core dependencies from the Maven setup. ```Java package com.itextpdf.hellopdf; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import java.io.FileNotFoundException; public class HelloPdfApp { public static void main(String[] args) throws FileNotFoundException { try (Document document = new Document(new PdfDocument(new PdfWriter("./hello-pdf.pdf")))) { document.add(new Paragraph("Hello PDF!")); } } } ``` -------------------------------- ### Create initial List object Source: https://kb.itextpdf.com/itext/chapter-4-adding-abstractelement-objects-part-1 Starts the nested list example by creating an ordinary list that will use hyphens as list symbols. ```Java List list = new List(); ``` -------------------------------- ### PdfUA example: main method to create PDF/UA document Source: https://kb.itextpdf.com/it5kb/how-can-i-generate-a-pdf-ua-compatible-pdf-with-it Entry point that creates the output directory and calls createPdf. Used in the PdfUA example to generate a PDF/UA compliant PDF. ```Java static public void main(String args[]) throws IOException, DocumentException { File file = new File(DEST); file.getParentFile().mkdirs(); new PdfUA().createPdf(DEST); } ``` -------------------------------- ### C# Hello World example (C01E01_HelloWorld) Source: https://kb.itextpdf.com/itext/itext-7-jump-start-tutorial-chapter-1 Creates a simple PDF with the text 'Hello World!' using iText 7 for .NET. Initializes a PdfWriter, PdfDocument, and Document, adds a Paragraph, and closes the document. The output file is written to '../../../results/chapter01/hello_world.pdf'. ```C# using System; using System.IO; using iText.Kernel.Pdf; using iText.Layout; using iText.Layout.Element; namespace Tutorial.Chapter01 { /// Simple Hello World example. public class C01E01_HelloWorld { public const String DEST = "../../../results/chapter01/hello_world.pdf"; public static void Main(String[] args) { FileInfo file = new FileInfo(DEST); file.Directory.Create(); new C01E01_HelloWorld().CreatePdf(DEST); } public virtual void CreatePdf(String dest) { //Initialize PDF writer PdfWriter writer = new PdfWriter(dest); //Initialize PDF document PdfDocument pdf = new PdfDocument(writer); // Initialize document Document document = new Document(pdf); //Add paragraph to the document document.Add(new Paragraph("Hello World!")); //Close document document.Close(); } } } ``` -------------------------------- ### View available commands with --help Source: https://kb.itextpdf.com/2data/itext-pdf2data-4-deployment Run this command to see the list of commands and parameters supported by the deployment helper script. Replace x.y.z with the script version you downloaded. ```bash kotlinc -script deploy-docker-compose-x.y.z.main.kts -- help ``` -------------------------------- ### Get image dimensions with getScaledWidth() and getScaledHeight() Source: https://kb.itextpdf.com/it5kb/how-to-show-an-image-with-large-dimensions-across- Retrieve the original width and height of the image before tiling. This is the first step in the TiledImage example to determine the size of each page. ```java Image image = Image.getInstance(IMAGE); float width = image.getScaledWidth(); float height = image.getScaledHeight(); ``` -------------------------------- ### Start the application with docker-compose up Source: https://kb.itextpdf.com/2data/itext-pdf2data-4-deployment Run this command in the folder containing docker-compose.yml and .env to start the application. ```bash docker-compose up -d ``` -------------------------------- ### Maven pom.xml dependencies for iText Core Source: https://kb.itextpdf.com/__attachments/a_93ff56ccde2c49903cce0250f8cf5b3bbbf414efc01f7966cb3a5fd0ef36eec1/README.pdf?cb=3f12a79fd3a5a3d964e8951433aca1cb Add these entries to your pom.xml to use iText Core with Maven. Replace REPLACE_WITH_DESIRED_ITEXT_VERSION with the version you want. The itext-core dependency is a POM type that pulls in the core modules, and bouncy-castle-adapter provides the Bouncy Castle cryptography adapter. ```XML REPLACE_WITH_DESIRED_ITEXT_VERSION com.itextpdf itext-core ${itext.version} pom com.itextpdf bouncy-castle-adapter ${itext.version} ``` -------------------------------- ### renderImage() method in MyImageRenderListener Source: https://kb.itextpdf.com/it5kb/how-to-get-the-coordinates-of-an-image Implements the RenderListener interface's renderImage() method to extract an image from a PDF using ImageRenderInfo and PdfImageObject. It writes the image bytes to a file and prints any IOException message. Use this as a starting point to access image coordinates via getImageCTM(). ```java public void renderImage(ImageRenderInfo renderInfo) { try { String filename; FileOutputStream os; PdfImageObject image = renderInfo.getImage(); if (image == null) return; filename = String.format(path, renderInfo.getRef().getNumber(), image.getFileType()); os = new FileOutputStream(filename); os.write(image.getImageAsBytes()); os.flush(); os.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } ``` -------------------------------- ### Java Hello World example (C01E01_HelloWorld) Source: https://kb.itextpdf.com/itext/itext-7-jump-start-tutorial-chapter-1 Creates a simple PDF with the text 'Hello World!' using iText 7. Initializes a PdfWriter, PdfDocument, and Document, adds a Paragraph, and closes the document. The output file is written to 'results/chapter01/hello_world.pdf'. ```Java /* This file is part of the iText (R) project. Copyright (c) 1998-2023 Apryse Group NV Authors: Apryse Software. For more information, please contact iText Software at this address: sales@itextpdf.com */ package tutorial.chapter01; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import java.io.File; import java.io.IOException; /** * Simple Hello World example. */ public class C01E01_HelloWorld { public static final String DEST = "results/chapter01/hello_world.pdf"; public static void main(String args[]) throws IOException { File file = new File(DEST); file.getParentFile().mkdirs(); new C01E01_HelloWorld().createPdf(DEST); } public void createPdf(String dest) throws IOException { //Initialize PDF writer PdfWriter writer = new PdfWriter(dest); //Initialize PDF document PdfDocument pdf = new PdfDocument(writer); // Initialize document Document document = new Document(pdf); //Add paragraph to the document document.add(new Paragraph("Hello World!")); //Close document document.close(); } } ``` -------------------------------- ### Get object from PdfArray using get(int, boolean) (iText 7) Source: https://kb.itextpdf.com/itext/how-do-i-get-an-object-if-i-have-its-indirect-refe In iText 7, use the get(int index, boolean asDirect) method with a false second parameter to retrieve an object as an indirect reference. The example gets the element at index 2. ```Java PdfObject o = array.get(2, false); ``` -------------------------------- ### PadesSigningExample class with Baseline B and LTA signing methods Source: https://kb.itextpdf.com/itext/pades-signing-high-level-api Shows the full C# example class for PAdES signing using PdfPadesSigner. Includes Baseline B profile signing (commented out) and Baseline LTA profile signing with TSA, CRL, and OCSP clients. Uses a helper class PemFileHelper to read certificate chains and private keys from PEM files. The example references certificate files under the resources folder and uses the password "testpassphrase". ```csharp public class PadesSigningExample{ public const String URI = "../../../resources/ReleaseExample/"; public const String CERTS_URI = URI + "certs/"; public const String PASSWORD = "testpassphrase"; public void BaselineBProfileExample(String inFile, String outFile){ String certPath = CERTS_URI+"certs/signCertRsa01.pem"; PdfPadesSigner padesSigner = new PdfPadesSigner(new PdfReader(inFile), new FileStream(outFile, FileMode.Create)); SignerProperties properties = new SignerProperties(); properties.SetFieldName("signatureField"); var chain = PemFileHelper.ReadFirstChain(certPath); var privateKey = PemFileHelper.ReadFirstKey(certPath, PASSWORD.ToCharArray()); var pkSig = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256); TSAClientBouncyCastle tsa = new TSAClientBouncyCastle("https://rfc3161.ai.moda"); // padesSigner.SignWithBaselineBProfile(properties, chain, pkSig); // padesSigner.SignWithBaselineLTAProfile(properties,chain,pkSig,tsa); } public void BaseLineLtaExample(String inFile, String outFile){ String srcFileName = URI + "helloWorldDoc.pdf"; String signCertFileName = CERTS_URI + "signCertRsa01.pem"; String caCertFileName = CERTS_URI +"rootRsa.pem"; PdfPadesSigner padesSigner = new PdfPadesSigner(new PdfReader(inFile), new FileStream(outFile, FileMode.Create)); SignerProperties properties = new SignerProperties(); properties.SetFieldName("signatureField"); IX509Certificate[] signRsaChain = PemFileHelper.ReadFirstChain(signCertFileName); IPrivateKey signRsaPrivateKey = PemFileHelper.ReadFirstKey(signCertFileName, PASSWORD.ToCharArray()); IX509Certificate caCert = (IX509Certificate)PemFileHelper.ReadFirstChain(caCertFileName)[0]; IPrivateKey caPrivateKey = PemFileHelper.ReadFirstKey(caCertFileName, PASSWORD.ToCharArray()); SignerProperties signerProperties = new SignerProperties(); TSAClientBouncyCastle tsa = new TSAClientBouncyCastle("https://rfc3161.ai.moda"); ICrlClient crlClient = new TestCrlClient().AddBuilderForCertIssuer(caCert, caPrivateKey); TestOcspClient ocspClient = new TestOcspClient().AddBuilderForCertIssuer(caCert, caPrivateKey); padesSigner.SetOcspClient(ocspClient) .SetCrlClient(crlClient); var privateKey = PemFileHelper.ReadFirstKey(signCertFileName, PASSWORD.ToCharArray()); var pkSig = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256); padesSigner.SignWithBaselineLTAProfile(signerProperties, signRsaChain, pkSig, tsa); } class PemFileHelper{ private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); private PemFileHelper(){ } public static IX509Certificate[] ReadFirstChain(String pemFileName){ return ReadCertificates(pemFileName).ToArray(new IX509Certificate[0]); } public static IPrivateKey ReadFirstKey(String pemFileName, char[] keyPass){ return ReadPrivateKey(pemFileName, keyPass); } public static List InitStore(String pemFileName){ IX509Certificate[] chain = ReadFirstChain(pemFileName); return chain.Length > 0 ? new List{chain[0]} : chain.ToList(); } private static IList ReadCertificates(String pemFileName){ using (TextReader file = new StreamReader(pemFileName)){ IPemReader parser = FACTORY.CreatePEMParser(file, null); Object readObject = parser.ReadObject(); IList certificates = new List(); while (readObject != null){ if (readObject is IX509Certificate){ certificates.Add((IX509Certificate) readObject); } readObject = parser.ReadObject(); } return certificates; } } private static IPrivateKey ReadPrivateKey(String pemFileName, char[] keyPass){ using (TextReader file = new StreamReader(pemFileName)){ IPemReader parser = FACTORY.CreatePEMParser(file, keyPass); Object readObject = parser.ReadObject(); while (!(readObject is IPrivateKey) && readObject != null){ readObject = parser.ReadObject(); } return (IPrivateKey) readObject; } } } } ``` -------------------------------- ### GET /pdf-producer/reports/{report-id} - Example request and response Source: https://kb.itextpdf.com/ditokb/itext-dito-docker-rest-api-vitext_dito_2-3 Example request and response for getting a cached PDF producer report by ID. The request uses a specific report ID and the response includes a templateRepairReport entry with a warning about an unexpected empty attribute. ```http GET localhost:42/api/pdf-producer/reports/65fff9f3-db63-4c6d-ad0f-81418b4376b7 Content-Type: application/json ``` ```http 200 OK Content-Type: application/json Body { "pageCount": 1, "templateRepairReport": { "entries": [ { "message": "Encountered unexpected empty attribute: 'data-dito-bind'", "severity": "warn" } ] }, "pdfProductionReport": { "entries": [] }, "id": "65fff9f3-db63-4c6d-ad0f-81418b4376b7", "highestSeverity": "warn" } ``` -------------------------------- ### PdfOptimizer C# configuration and optimization example Source: https://kb.itextpdf.com/itext/pdfoptimizer-support-added-for-font-image-color-sp Shows how to load the license, configure optimization handlers (font deduplication, font subsetting, image quality, compression, and RGB-to-CMYK color conversion), set up a report builder, and run the optimizer on a document. Requires a valid iText license file and input/output file paths. ```C# using iText.License; using iText.Pdfoptimizer; using iText.Pdfoptimizer.Handlers; using iText.Pdfoptimizer.Handlers.Converters; using iText.Pdfoptimizer.Handlers.Imagequality.Processors; using iText.Pdfoptimizer.Report.Builder; using iText.Pdfoptimizer.Report.Message; using iText.Pdfoptimizer.Report.Publisher; using System.IO; namespace itext_dev.Optimizer_Demo { class PdfOptimizer_Sample { public static void Main() { PdfOptimizer_Sample test = new PdfOptimizer_Sample(); test.PdfOptimizerTest(); } public void PdfOptimizerTest() { // First, we must load our license file in order to utilize pdfOptimizer. LicenseKey.LoadLicenseFile("iText7_licensekey.xml"); // As the namesake class of the PdfOptimizer add-on, this is where we configure our optimization. PdfOptimizer optimizer = new PdfOptimizer(); /* Here we instantiate a FileReportBuilder which we can use as a log of the efficacy of our optimization. Security level configuration possible. */ FileReportPublisher publisher = new FileReportPublisher(new FileInfo("report.txt")); FileReportBuilder builder = new FileReportBuilder(SeverityLevel.INFO, publisher); optimizer.SetReportBuilder(builder); /* From here on, we configure how PdfOptimizer will optimize our documents. Each handler represents a different optimization strategy */ // Removes duplicate instances of font files embedded within documents. optimizer.AddOptimizationHandler(new FontDuplicationOptimizer()); // Removes all character data per font which is not actively utilized in the input document. optimizer.AddOptimizationHandler(new FontSubsettingOptimizer()); /* Scales down and compresses Image objects. In this case, we scale and compress a Tiff image by 50% */ ImageQualityOptimizer tiff_optimizer = new ImageQualityOptimizer(); tiff_optimizer.SetTiffProcessor(new BitmapCompressor(.5f, .5f)); optimizer.AddOptimizationHandler(tiff_optimizer); // Here, we add a general compression strategy on our entire document based on Deflater logic. optimizer.AddOptimizationHandler(new CompressionOptimizer()); /* Adds a handler to our optimization process to convert our input document's colorspace from RGB, to CMYK. */ ColorSpaceConverter rgbToCmykConverter = new ColorSpaceConverter(); CsConverterProperties csConversionProperties = new CsConverterProperties(ColorConversionMode.NORMAL); rgbToCmykConverter.SetCsConverter(new RgbToCmykCsConverter(csConversionProperties)); optimizer.AddOptimizationHandler(rgbToCmykConverter); // Document is optimized according to defined handlers and written out to file. optimizer.Optimize( new FileInfo(SRC, FileMode.Open), new FileInfo(DEST, FileMode.Create, FileAccess.Write)); } } } ``` -------------------------------- ### C#: PdfPadesSigner example (partial) Source: https://kb.itextpdf.com/itext/pades-signing-high-level-api Partial C# example showing the using directives for PdfPadesSigner with iText and BouncyCastle. The code is incomplete and does not include the full signing logic. ```C# using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Bouncycastle.Openssl; using iText.Commons.Utils; using iText.Kernel.Pdf; using iText.Signatures; using itext8_project.s81866; using Org.BouncyCastle.Pkcs; namespace itext8_project.ReleaseExample.itext802; ``` -------------------------------- ### Apply clipping path to create rounded corners (C# port of ClippingPath example) Source: https://kb.itextpdf.com/it5kb/how-to-give-an-image-rounded-corners Demonstrates how to clip an image to an ellipse using a PdfTemplate and the DirectContent. The example creates a template with the image's scaled dimensions, draws an ellipse, applies a clip, and adds the image. To get rounded corners instead of an ellipse, replace the Ellipse() method with RoundRectangle(). Note the AddImage call uses a y-offset of -600, which may need adjustment for your image. ```csharp Image img = Image.GetInstance(some_path_to_an_image); float w = img.ScaledWidth; float h = img.ScaledHeight; PdfTemplate t = writer.DirectContent.CreateTemplate(w, h); t.Ellipse(0, 0, w, h); t.Clip(); t.NewPath(); t.AddImage(img, w, 0, 0, h, 0, -600); Image clipped = Image.GetInstance(t); ``` -------------------------------- ### GetFittingRows Source: https://kb.itextpdf.com/it5kb/pdfptable-1 Gets the fitting rows for the given available height and start index. ```APIDOC ## GetFittingRows ### Description Gets the fitting rows for the given available height and start index. ### Method public virtual FittingRows GetFittingRows(float availableHeight, int startIdx) ### Parameters - **availableHeight** (float) - Required - The available height. - **startIdx** (int) - Required - The start index. ### Returns - **FittingRows** - The fitting rows object. ``` -------------------------------- ### Java: C01E03_QuickBrownFox - Add images to a Paragraph Source: https://kb.itextpdf.com/itext/itext-7-jump-start-tutorial-chapter-1 Creates a PDF with a Paragraph containing two images (fox.bmp and dog.bmp) using iText 7. The example initializes a PdfWriter, PdfDocument, and Document, then adds a Paragraph composed of text and Image elements. Requires the image files at the specified paths and writes the output to results/chapter01/quick_brown_fox.pdf. ```java /* This file is part of the iText (R) project. Copyright (c) 1998-2023 Apryse Group NV Authors: Apryse Software. For more information, please contact iText Software at this address: sales@itextpdf.com */ package tutorial.chapter01; import com.itextpdf.io.image.ImageDataFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Image; import com.itextpdf.layout.element.Paragraph; import java.io.File; import java.io.IOException; /** * Simple image example. */ public class C01E03_QuickBrownFox { public static final String DOG = "src/main/resources/img/dog.bmp"; public static final String FOX = "src/main/resources/img/fox.bmp"; public static final String DEST = "results/chapter01/quick_brown_fox.pdf"; public static void main(String args[]) throws IOException { File file = new File(DEST); file.getParentFile().mkdirs(); new C01E03_QuickBrownFox().createPdf(DEST); } public void createPdf(String dest) throws IOException { //Initialize PDF writer PdfWriter writer = new PdfWriter(dest); //Initialize PDF document PdfDocument pdf = new PdfDocument(writer); // Initialize document Document document = new Document(pdf); // Compose Paragraph Image fox = new Image(ImageDataFactory.create(FOX)); Image dog = new Image(ImageDataFactory.create(DOG)); Paragraph p = new Paragraph("The quick brown ") .add(fox) .add(" jumps over the lazy ") .add(dog); // Add Paragraph to document document.add(p); //Close document document.close(); } } ``` -------------------------------- ### GetCellStartRowIndex Source: https://kb.itextpdf.com/it5kb/pdfptable-1 Gets the start row index of a cell at the specified row and column. ```APIDOC ## GetCellStartRowIndex ### Description Gets the start row index of a cell at the specified row and column. ### Method public virtual int GetCellStartRowIndex(int rowIdx, int colIdx) ### Parameters - **rowIdx** (int) - Required - The row index. - **colIdx** (int) - Required - The column index. ### Returns - **int** - The start row index of the cell. ``` -------------------------------- ### C#: C01E03_QuickBrownFox - Add images to a Paragraph Source: https://kb.itextpdf.com/itext/itext-7-jump-start-tutorial-chapter-1 C# version of the same example, creating a PDF with a Paragraph containing two images. Uses iText 7 .NET classes (PdfWriter, PdfDocument, Document, Image, Paragraph) and writes to ../../../results/chapter01/quick_brown_fox.pdf. The image paths are relative to the project's resources folder. ```csharp using System; using System.IO; using iText.IO.Image; using iText.Kernel.Pdf; using iText.Layout; using iText.Layout.Element; namespace Tutorial.Chapter01 { /// Simple image example. public class C01E03_QuickBrownFox { public const String DOG = "../../../resources/img/dog.bmp"; public const String FOX = "../../../resources/img/fox.bmp"; public const String DEST = "../../../results/chapter01/quick_brown_fox.pdf"; public static void Main(String[] args) { FileInfo file = new FileInfo(DEST); file.Directory.Create(); new C01E03_QuickBrownFox().CreatePdf(DEST); } public virtual void CreatePdf(String dest) { //Initialize PDF writer PdfWriter writer = new PdfWriter(dest); //Initialize PDF document PdfDocument pdf = new PdfDocument(writer); // Initialize document Document document = new Document(pdf); // Compose Paragraph iText.Layout.Element.Image fox = new Image(ImageDataFactory.Create(FOX)); iText.Layout.Element.Image dog = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); Paragraph p = new Paragraph("The quick brown ").Add(fox).Add(" jumps over the lazy ").Add(dog); // Add Paragraph to document document.Add(p); //Close document document.Close(); } } } ``` -------------------------------- ### Get cached PDF producer report - Request Source: https://kb.itextpdf.com/ditokb/itext-dito-docker-rest-api-vitext_dito_2-3 Example request to get a cached PDF producer report. Uses localhost:42 and a specific report ID. ```http GET localhost:42/api/pdf-producer/reports/65fff9f3-db63-4c6d-ad0f-81418b4376b7 Content-Type: application/json ``` -------------------------------- ### HelloWorld example: create a PDF with a Paragraph Source: https://kb.itextpdf.com/itext/chapter-1-introducing-basic-building-blocks-net Creates a PDF document with the text 'Hello World!' using PdfWriter, PdfDocument, and Document. The PdfWriter accepts a file path string or a Stream (e.g., HttpResponse.OutputStream or MemoryStream). Closing the document finalizes the PDF. ```C# var writer = new PdfWriter(dest); var pdf = new PdfDocument(writer); var document = new Document(pdf); document.Add(new Paragraph("Hello World!")); document.Close(); ``` -------------------------------- ### Gradle commands to build and run Source: https://kb.itextpdf.com/itext/how-to-load-itext-licenses-correctly-with-gradle Use these commands to build and run your project. Check the console output to confirm the license files have been loaded successfully. ```bash ./gradlew build ./gradlew run ``` -------------------------------- ### PdfPTable.GetRows Source: https://kb.itextpdf.com/it5kb/pdfptable-1 Gets a list of rows from the start index to the end index. This is used to access a range of rows. ```APIDOC ## [GetRows] [PdfPTable.GetRows] ### Description Gets a list of rows from the start index to the end index. ### Method GetRows ### Parameters - **start** (int) - Required - The start index. - **end** (int) - Required - The end index. ### Returns List - The list of rows. ``` -------------------------------- ### PdfPTable.GetFittingRows Source: https://kb.itextpdf.com/it5kb/pdfptable-1 Gets the rows that fit within the available height starting from the given index. This is used for layout. ```APIDOC ## [GetFittingRows] [PdfPTable.GetFittingRows] ### Description Gets the rows that fit within the available height. ### Method GetFittingRows ### Parameters - **availableHeight** (float) - Required - The available height. - **startIdx** (int) - Required - The starting row index. ### Returns FittingRows - The fitting rows. ``` -------------------------------- ### Example 2: Creating a List with ListItem and String Source: https://kb.itextpdf.com/it5kb/listitem Creates a List with unordered items and adds a ListItem and a plain string to it. ```csharp List overview = new List(false, 10); overview.Add(new ListItem("This is an item")); overview.Add("This is another item"); ``` -------------------------------- ### Output of FormInformation example on datasheet.pdf Source: https://kb.itextpdf.com/it5kb/how-to-get-specific-types-from-acrofields-like-pus This is the output produced when running the FormInformation example on datasheet.pdf. It lists each field name with its type and the possible appearance states for fields 'CP_1' and 'category'. ```text title: Text category: Radiobutton director: Text MA_2: Checkbox CP_2: Checkbox GP_3: Checkbox MA_3: Checkbox GP_8: Checkbox year: Text CP_1: Checkbox GP_4: Checkbox CP_3: Checkbox GP_7: Checkbox duration: Text Possible values for CP_1: - Off - Yes Possible values for category: Off, comp, fest, fdir, kubr, kuro, zha, lee, kim, toro, worl, fran, scan, s-am, spec, teen, anim, kauf, rive, hero ``` -------------------------------- ### Main method loading license and creating PDF (Java and C#) Source: https://kb.itextpdf.com/itext/chapter-1-hello-html-to-pdf Loads the iText license file from the ITEXT7_LICENSEKEY environment variable, creates the target directory, and calls createPdf(). The C# version uses Environment.GetEnvironmentVariable and Directory.CreateDirectory. ```Java public static void main(String[] args) throws IOException { LicenseKey.loadLicenseFile( System.getenv("ITEXT7_LICENSEKEY") + "/itextkey-html2pdf_typography.xml"); File file = new File(TARGET); file.mkdirs(); new C01E01_HelloWorld().createPdf(HTML, DEST); } ``` ```C# static void Main(string[] args) { LicenseKey.LoadLicenseFile( Environment.GetEnvironmentVariable("ITEXT-7_LICENSEKEY") + "\\itextkey-html2pdf_typography.xml" ); Directory.CreateDirectory(BASEURI); new C01E01_HelloWorld().createPdf(HTML, DEST); } ``` -------------------------------- ### C03E02_PremierLeague: Java table renderer example Source: https://kb.itextpdf.com/itext/itext-7-jump-start-tutorial-chapter-3 Full Java example from the iText 7 jump-start tutorial (Chapter 3, c03e02_premierleague). It reads a CSV file (premier_league.csv) and builds a PDF table with custom cell colors and a rounded-corner cell renderer. Uses DeviceCmyk colors, StandardFonts.HELVETICA, and a custom CellRenderer subclass. The main method creates the output PDF at results/chapter03/premier_league.pdf. ```java /* This file is part of the iText (R) project. Copyright (c) 1998-2023 Apryse Group NV Authors: Apryse Software. For more information, please contact iText Software at this address: sales@itextpdf.com */ package tutorial.chapter03; import com.itextpdf.io.font.constants.StandardFonts; import com.itextpdf.kernel.colors.Color; import com.itextpdf.kernel.colors.ColorConstants; import com.itextpdf.kernel.colors.DeviceCmyk; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.geom.PageSize; import com.itextpdf.kernel.geom.Rectangle; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; import com.itextpdf.layout.Document; import com.itextpdf.layout.properties.HorizontalAlignment; import com.itextpdf.layout.borders.SolidBorder; import com.itextpdf.layout.element.Cell; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.element.Table; import com.itextpdf.layout.properties.TextAlignment; import com.itextpdf.layout.properties.UnitValue; import com.itextpdf.layout.renderer.CellRenderer; import com.itextpdf.layout.renderer.DrawContext; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.StringTokenizer; /** * Simple table renderer example. */ public class C03E02_PremierLeague { public static final String DATA = "src/main/resources/data/premier_league.csv"; public static final String DEST = "results/chapter03/premier_league.pdf"; Color greenColor = new DeviceCmyk(0.78f, 0, 0.81f, 0.21f); Color yellowColor = new DeviceCmyk(0, 0, 0.76f, 0.01f); Color redColor = new DeviceCmyk(0, 0.76f, 0.86f, 0.01f); Color blueColor = new DeviceCmyk(0.28f, 0.11f, 0, 0); public static void main(String args[]) throws IOException { File file = new File(DEST); file.getParentFile().mkdirs(); new C03E02_PremierLeague().createPdf(DEST); } public void createPdf(String dest) throws IOException { //Initialize PDF document PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); PageSize ps = new PageSize(842, 680); // Initialize document Document document = new Document(pdf, ps); PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA); PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD); Table table = new Table(UnitValue.createPercentArray(new float[]{1.5f, 7, 2, 2, 2, 2, 3, 4, 4, 2})); table .setTextAlignment(TextAlignment.CENTER) .setHorizontalAlignment(HorizontalAlignment.CENTER); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(DATA), StandardCharsets.UTF_8)); String line = br.readLine(); process(table, line, bold, true); while ((line = br.readLine()) != null) { process(table, line, font, false); } br.close(); document.add(table); //Close document document.close(); } public void process(Table table, String line, PdfFont font, boolean isHeader) { StringTokenizer tokenizer = new StringTokenizer(line, ";"); int columnNumber = 0; while (tokenizer.hasMoreTokens()) { if (isHeader) { Cell cell = new Cell().add(new Paragraph(tokenizer.nextToken())); cell.setNextRenderer(new RoundedCornersCellRenderer(cell)); cell.setPadding(5).setBorder(null); table.addHeaderCell(cell); } else { columnNumber++; Cell cell = new Cell().add(new Paragraph(tokenizer.nextToken())); cell.setFont(font).setBorder(new SolidBorder(ColorConstants.BLACK, 0.5f)); switch (columnNumber) { case 4: cell.setBackgroundColor(greenColor); break; case 5: cell.setBackgroundColor(yellowColor); break; case 6: cell.setBackgroundColor(redColor); break; default: cell.setBackgroundColor(blueColor); break; } table.addCell(cell); } } } private class RoundedCornersCellRenderer extends CellRenderer { public RoundedCornersCellRenderer(Cell modelElement) { super(modelElement); } ``` -------------------------------- ### Retrieve UserUnit from page dictionary Source: https://kb.itextpdf.com/it5kb/how-to-get-the-userunit-from-a-pdf-file Gets the /UserUnit value from a page's dictionary using PdfReader.GetPageN and PdfName.USERUNIT. The value is a PdfNumber, often null if not present; use FloatValue to get the numeric value. This key is optional and only exists in PDF 1.6 or later. ```csharp PdfDictionary pageDict = reader.GetPageN(i); PdfNumber userUnit = pageDict.GetAsNumber(PdfName.USERUNIT); ``` -------------------------------- ### Create environment configuration file (.env) Source: https://kb.itextpdf.com/2data/itext-pdf2data-4-deployment Creates an environment configuration file (.env) for the specified deployment mode. The --manager-admin-password parameter prompts for a global admin password (12-64 characters). Optionally use --multi-workspace-mode for multi-workspace support (full application mode only). ```bash kotlinc -script deploy-docker-compose-x.y.z.main.kts -- create-config-file --mode=editor-standalone|full-application --manager-admin-password [--multi-workspace-mode] ``` -------------------------------- ### PdfPTable.GetCellStartRowIndex Source: https://kb.itextpdf.com/it5kb/pdfptable-1 Gets the start row index of a cell at the given row and column. This is used to determine cell spanning. ```APIDOC ## [GetCellStartRowIndex] [PdfPTable.GetCellStartRowIndex] ### Description Gets the start row index of a cell. ### Method GetCellStartRowIndex ### Parameters - **rowIdx** (int) - Required - The row index. - **colIdx** (int) - Required - The column index. ### Returns int - The start row index. ``` -------------------------------- ### Hello World with System.Console in Python.NET Source: https://kb.itextpdf.com/itext/how-to-use-itext-in-python-environments Initializes the .NET runtime via the clr module and writes a message to the console using System.Console. Requires the pythonnet package installed. ```Python import clr from System import Console Console.WriteLine("Hello, World!") ``` -------------------------------- ### Get page dimensions in points with PdfReader Source: https://kb.itextpdf.com/it5kb/how-to-get-the-userunit-from-a-pdf-file Retrieves the page size (MediaBox) for each page in a PDF using iTextSharp's PdfReader. The dimensions are in points (user units), which may need to be multiplied by the UserUnit value to get pixels. Note that GetPageSize returns the MediaBox, not the CropBox if defined. ```csharp PdfReader reader = new iTextSharp.text.pdf.PdfReader(file_content); for (int i = 1; i reader.NumberOfPages; i++) { Rectangle dim = reader.GetPageSize(i); int[] xy = new int[] { (int)dim.Width, (int)dim.Height }; page_data[objectid + '-' + i] = xy; } ``` -------------------------------- ### Destination array examples (PDF syntax) Source: https://kb.itextpdf.com/itext/how-to-get-the-page-number-of-an-arbitrary-pdf-obj Two destination array examples. The first has two elements (reference and /Fit), the second has five elements (reference, /XYZ, and coordinates). The first element is a reference to a /Page object. ```Java [8 0 R/Fit] ``` ```Java [6 0 R/XYZ 0 806 0] ``` -------------------------------- ### ENTRYPOINT ["/opt/dito/startup.sh"] Source: https://kb.itextpdf.com/ditokb/itext-dito-docker-api-vitext_dito_2-0 Shown as unnecessary because the base image already provides this entrypoint. You only need to call /opt/dito/startup.sh at the end of your own script if you want to run custom logic before DITO starts. ```dockerfile ENTRYPOINT ["/opt/dito/startup.sh"] ``` -------------------------------- ### RemoveXFA example (C# / iTextSharp) Source: https://kb.itextpdf.com/it5kb/how-to-change-the-text-color-of-an-acroform-field C# version of the RemoveXFA example. Removes the XFA stream, sets text color to red for fields with 'Total' in their name, and fills all fields with 'X'. ```csharp public void ManipulatePdf(String src, String dest) { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)); AcroFields form = stamper.AcroFields; form.RemoveXfa(); IDictionary fields = form.Fields; foreach (String name in fields.Keys) { if (name.IndexOf("Total") > 0) form.SetFieldProperty(name, "textcolor", BaseColor.RED, null); form.SetField(name, "X"); } stamper.Close(); reader.Close(); } ``` -------------------------------- ### Create standard OutlineHandler for bookmarks (C#) Source: https://kb.itextpdf.com/itext/chapter-4-creating-reports-using-pdfhtml Equivalent .NET version using OutlineHandler.CreateStandardHandler() and ConverterProperties.SetOutlineHandler(). ```C# public void CreatePdf(byte[] html, string baseUri, string dest) { ConverterProperties properties = new ConverterProperties(); PdfWriter writer = new PdfWriter(dest); PdfDocument pdf = new PdfDocument(writer); OutlineHandler outlineHandler = OutlineHandler.CreateStandardHandler(); properties.SetOutlineHandler(outlineHandler); properties.SetBaseUri(baseUri); HtmlConverter.ConvertToPdf(new MemoryStream(html), new FileStream(dest, FileMode.Create), properties); } ``` -------------------------------- ### GET 404 Not Found response Source: https://kb.itextpdf.com/ditokb/itext-dito-docker-rest-api-vitext_dito_2-4 Example error response when the deployed template with the specified alias is not found. ```json { "message": "HTTP 404 Not Found", "code": 404 } ``` -------------------------------- ### Default DITO SDK entrypoint command Source: https://kb.itextpdf.com/ditokb/itext-dito-deploying-sdk The base image entrypoint runs the preparation script and then starts the DITO application. You do not need to write this yourself; it is provided for reference if you want to run additional commands before the DITO application starts. ```dockerfile ENTRYPOINT ["bash", "-c", "source $HOME/.sdkman/bin/sdkman-init.sh && kotlin /opt/dito/startup.prepare.main.kts && java -jar /opt/dito/$DITO\_JAR\_NAME server /etc/opt/dito/config.yml"] ``` -------------------------------- ### GET /pdf-producer/reports - Example response: List of PDF producer report descriptors Source: https://kb.itextpdf.com/ditokb/itext-dito-docker-rest-api-vitext_dito_2-3 Example 200 response for the getReports endpoint. Shows the structure of a PDF producer report descriptor, including pageCount, templateRepairReport, pdfProductionReport, id, timestamp, and highestSeverity. ```json [ { "pageCount": 1, "templateRepairReport": { "entries": [] }, "pdfProductionReport": { "entries": [] }, "id": "6fefa7b6-282e-474e-892d-78aa886e18a0", "timestamp": "2021-11-23T09:09:07.331355100Z", "highestSeverity": null } ] ``` -------------------------------- ### Create PAdES-B-B signature with PadesTwoPhaseSigningHelper Source: https://kb.itextpdf.com/itext/pades-signing-high-level-api Shows how to create a PAdES level B signature using the PadesTwoPhaseSigningHelper class. The example loads a PKCS#12 keystore, sets up a BouncyCastle provider, and uses a TSA client. Note the code contains minor inconsistencies (e.g., 'digestAlgorithm' vs 'digestAlgorithmn', missing semicolons) as it appears in the source. ```Java public void twoPhaseSigningExample(String inFile, String outFile) throws IOException, GeneralSecurityException { String certPath = "src/main/resources/release/testcert.pfx"; String password = "password"; String digestAlgorithmn = DigestAlgorithms.SHA384; PdfReader reader = new PdfReader(inFile); FileOutputStream fos = new FileOutputStream(outFile) PadesTwoPhaseSigningHelper signingHelper = new PadesTwoPhaseSigningHelper(); SignerProperties properties = new SignerProperties(); properties.setFieldName("signatureField"); BouncyCastleProvider providerBC = new BouncyCastleProvider(); Security.addProvider(providerBC); KeyStore ks = KeyStore.getInstance("pkcs12"); InputStream fis = Files.newInputStream(Paths.get(certPath)); ks.load(fis, password.toCharArray()); String alias = ks.aliases().nextElement(); Certificate[] chain = ks.getCertificateChain(alias); PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray()); TSAClientBouncyCastle tsa = new TSAClientBouncyCastle("https://rfc3161.ai.moda"); IExternalSignature externalSignature = new PrivateKeySignature(pk, digestAlgorithm, provider); CMSContainer signatureContainer = signingHelper.createCMSContainerWithoutSignature(chain, digestAlgorithmn, reader, fos, signerProperties) signingHelper.signCMSContainerWithBaselineBProfile(externalSignature, reader, fos, "signatureField", signatureContainer ) } ``` -------------------------------- ### List Kubernetes contexts Source: https://kb.itextpdf.com/ditokb/deploying-itext-dito-editor-and-manager-with-kub-1 Displays a list of available Kubernetes contexts. Run this command after configuring kubectl access to the cluster. ```bash kubectl config get-contexts ``` -------------------------------- ### Example 2: Same as Example 1 but with 50% table width Source: https://kb.itextpdf.com/it5kb/how-to-add-inline-spacing-in-a-pdfpcell Variation of Example 1 with table.setWidthPercentage(50) instead of 60. With equal column widths, the longer label "Received Rs (in Words):" wraps because it doesn't fit; defining a larger width for the first column would avoid wrapping. ```java // same code as above, except for: table.setWidthPercentage(50); ``` -------------------------------- ### Example 1: Creating a List with ListItems Source: https://kb.itextpdf.com/it5kb/listitem Creates a List with numbered items and adds three ListItem objects. The second item is longer to demonstrate line wrapping behavior. ```csharp List list = new List(true, 20); list.Add(new ListItem("First line")); list.Add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?")); list.Add(new ListItem("Third line")); ``` -------------------------------- ### Dockerfile FROM itext/dito-sdk-secure-proxy Source: https://kb.itextpdf.com/ditokb/deploy-itext-dito-secure-proxy-optional Start a custom Dockerfile by extending the secure proxy image. Example uses version 1.5.9. ```dockerfile FROM itext/dito-sdk-secure-proxy:1.5.9 ``` -------------------------------- ### Deploy the application Source: https://kb.itextpdf.com/2data/itext-pdf2data-4-deployment Deploys the application using the created Docker Compose and configuration files. The script pulls the necessary Docker images (Manager front-end, back-end, database, and pdf2Data Editor). Execution may take a while. ```bash kotlinc -script deploy-docker-compose-x.y.z.main.kts -- deploy ``` -------------------------------- ### Destination array examples (PDF syntax) Source: https://kb.itextpdf.com/it5kb/how-to-get-the-page-number-of-an-arbitrary-pdf-obj These are examples of destination arrays. The first has two elements (a page reference and /Fit), the second has five elements (a page reference, /XYZ, and three numbers). The first element is always a reference to a /Page object. ```pdf [8 0 R/Fit] [6 0 R/XYZ 0 806 0] ``` -------------------------------- ### GET /pdf-producer/reports/{report-id} - Example response: Requested PDF producer report descriptor Source: https://kb.itextpdf.com/ditokb/itext-dito-docker-rest-api-vitext_dito_2-3 Example 200 response for the getReport endpoint. Shows the structure of a PDF producer report descriptor, including pageCount, templateRepairReport, pdfProductionReport, id, timestamp, and highestSeverity. ```json { "pageCount": 1, "templateRepairReport": { "entries": [] }, "pdfProductionReport": { "entries": [] }, "id": "6fefa7b6-282e-474e-892d-78aa886e18a0", "timestamp": "2021-11-23T09:09:07.331355100Z", "highestSeverity": null } ``` -------------------------------- ### Get object from PdfArray using getAsX() methods (iText 5) Source: https://kb.itextpdf.com/itext/how-do-i-get-an-object-if-i-have-its-indirect-refe Use the getAsX() methods on a PdfArray to retrieve elements as a specific type when you have an indirect reference. The example retrieves a PdfDictionary at index 0, a PdfArray at index 1, and a PdfStream at index 2. ```Java PdfDictionary d = array.getAsDictionary(0); PdfArray a = array.getAsArray(1); PdfStream s = array.getAsStream(2); ``` -------------------------------- ### Python type hinting example (greeting function) Source: https://kb.itextpdf.com/itext/how-to-use-itext-in-python-environments Shows basic Python 3.5+ type hinting syntax used to bring static typing to Python. The surrounding text uses this to explain how IDEs and tools like mypy use type information, and how stub files (pyi) can provide typing separately. ```Python def greeting(name: str) -> str: return 'Hello ' + name ```