Home > Articles > Details

How to Write to PDF using an Open Source Library called iText 7 in Asp.Net Core [Writer Library (iText7 AGPL License)]

How to Write to PDF using iText7 Open Source PDF Library in C#Click to Watch Video

Question: How do I use the #PDF Library called iText 7 to write to the pdf in C-sharp?


Please Login to see the rest of the answer
Answer: Follow the steps below to write to the PDF using #iText7 Open Source PDF Library

  1. Create a PDF Writer Instance
     //Initialize PDF writer
     PdfWriter writer = new PdfWriter(location);?

     

  2. Initialize PDF document
     PdfDocument pdf = new PdfDocument(writer);?
  3. Initialize document
    Document document = new(pdf);?
  4. Add Image to PDF using iText Sharp or iText 7 Open Source PDF Library
      Image logo = new Image(ImageDataFactory.Create(logoPath));
                logo.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                document.Add(logo);?
  5. Loop through a list of items and append a Paragraph to the PDF using iText7 Open Source PDF Library in C-Sharp
    for (int i = 0; i < items.Count; i++)
     {
          document.Add(new Paragraph(items[i][0].ToString()));
     }?
  6. Close the PDF Document when you are done writing to the Stream
    document.Close();?
  7. See the Complete Function that writes to the PDF using iText 7 in C-Sharp and Asp.Net Core
    private void createPdf(String dest, string logoPath, List<string[]> items)
            {
                //Initialize PDF writer
                PdfWriter writer = new PdfWriter(dest);
    
                //Initialize PDF document
                PdfDocument pdf = new PdfDocument(writer);
    
                // Initialize document
                Document document = new(pdf);
                document.SetFontSize(14);
                document.SetTextAlignment(TextAlignment.CENTER);
                //Add paragraph to the document
                Image logo = new Image(ImageDataFactory.Create(logoPath));
                logo.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                document.Add(logo);
                for (int i = 0; i < items.Count; i++)
                {
                    document.Add(new Paragraph(items[i][0].ToString()));
                }
    
    
                //Close document
                document.Close();
            }?


    Documentation to PDF library in C# called iText 7, a library under AGPL license for Software Distribution. Link Here

    If this was helpful, please leave us a comment or sign up for an account so you get notified when a new article is created.

If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.


© 2022 - ErnesTech - Privacy