Home > Enterprise >  Creating a blank pdf and uploading an image to each page
Creating a blank pdf and uploading an image to each page

Time:06-20

I am new to file handling in asp.net core 6.0. I want to create a blank pdf and load images from the ImagePath list into it. Using the resources on the internet, I tried to create a blank pdf and throw it into it, but in vain. I couldn't use pdfReader inside pdfStamper. It was the only resource on the Internet that I found suitable for myself.

Link to the question; Converting Multiple Images into Multiple Pages PDF using itextsharp

How can I do that my code is below.

public static string MainStamping(string docname, List < string > imagePath, string mediaField) {
    var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
    var webRootPath = config["AppSettings:urunResimPath"].ToString();
    string filename = webRootPath   "\\menupdf\\"   docname   ".pdf";
    //            yeniisim = yeniisim   filelist.FileName;
    //            var fileName = "menupdf\\"   yeniisim;

    FileStream pdfOutputFile = new FileStream(filename, FileMode.Create);
    PdfConcatenate pdfConcatenate = new PdfConcatenate(pdfOutputFile);

    PdfReader result = null;

    for (int i = 0; i < imagePath.Count; i  ) {
        result = CreatePDFDocument1(imagePath[i], mediaField);
        pdfConcatenate.AddPages(result);
    }

    pdfConcatenate.Close();
    return filename;
}

public static PdfReader CreatePDFDocument1(string imagePath, string mediaField) {
    PdfReader pdfReader = null;

    //C:\Users\hilal\OneDrive\Belgeler\GitHub\Restaurant\Cafe.Web\wwwroot\assets\barkod-menu
    var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
    var webRootPath = config["AppSettings:urunResimPath"].ToString();
    string image = webRootPath   "\\barkod-menu\\"   imagePath;
    iTextSharp.text.Image instanceImg = iTextSharp.text.Image.GetInstance(image);

    MemoryStream inputStream = new MemoryStream();

    inputStream.Seek(0, SeekOrigin.Begin); //I don't know what to do here do I need to use it?
    pdfReader = new PdfReader(inputStream);

    MemoryStream memoryStream = new MemoryStream();
    PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream);

    AcroFields testForm = pdfStamper.AcroFields;
    testForm.SetField("MediaField", mediaField);

    PdfContentByte overContent = pdfStamper.GetOverContent(1);
    IList < AcroFields.FieldPosition > fieldPositions = testForm.GetFieldPositions("ImageField");

    if (fieldPositions == null || fieldPositions.Count <= 0) throw new ApplicationException("Error locating field");
    AcroFields.FieldPosition fieldPosition = fieldPositions[0];

    overContent.AddImage(instanceImg);
    pdfStamper.FormFlattening = true;
    pdfStamper.Close();

    PdfReader resultReader = new PdfReader(memoryStream.ToArray());
    pdfReader.Close();

    return resultReader;
}

visual

If I want to explain visually, the blank pdf I created will be uploaded in this way. Thank you

CodePudding user response:

The following shows how to create a PDF using iTextSharp (v. 5.5.13.3), and add images to the PDF (one image per page). It's been tested with .NET 6.

Pre-requisite:

  • Download / install NuGet package iTextSharp (v. 5.5.13.3)

Add the following using statements:

  • using iTextSharp.text;
  • using iTextSharp.text.pdf;
  • using System.IO;

In the code below the PDF is saved to a byte array, instead of a file to allow for more options.

CreatePdfDocument:

public static byte[] CreatePdfDocument(List<string> imagePaths)
{
    byte[] pdfBytes;

    using (MemoryStream ms = new MemoryStream())
    {
        using (Document doc = new Document(PageSize.LETTER, 1.0f, 1.0f, 1.0f, 1.0f))
        {
            using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
            {
                //open
                doc.Open();

                //create a new page for each image
                for (int i = 0; i < imagePaths.Count; i  )
                {
                    //add new page
                    doc.NewPage();

                    //get image
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePaths[i]);

                    //ToDo: set desired image size
                    //img.ScaleAbsolute(100.0f, 100.0f);

                    //center image on page
                    img.SetAbsolutePosition((PageSize.LETTER.Width - img.ScaledWidth) / 2, (PageSize.LETTER.Height - img.ScaledHeight) / 2);

                    //add image to page
                    doc.Add(img);
                }

                //close
                doc.Close();

                //convert MemoryStream to byte[]
                pdfBytes = ms.ToArray();
            }
        }    
    }

    return pdfBytes;
}

I've decided that all I want to do is write the PDF to a file. The method below writes the PDF to a file.

CreatePdf:

public static void CreatePdf(string filename, List<string> imagePaths)
{
    //create PDF
    byte[] pdfBytes = CreatePdfDocument(imagePaths);

    //save PDF to file
    System.IO.File.WriteAllBytes (filename, pdfBytes);   
}

Resources:

Additional Resources:

  • Related