Search code examples
c#seleniumitextvisual-studio-2019itext7

Having permission issues when using itext7 to convert PNG files to PDFs, some commands seems to have access others dont


https://itextpdf.com/en/demos/convert-image-to-pdf-free-online

I got the demo code on how to do it from their site, I am building this in c# visual studio, with selenium/ nunit

It seems pretty straight forward, but im getting some issue that I dont understand. Here is my code:

using System;
using iText.IO.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace TesingPDFConvert
{

        internal class Program
        {
            private static string ORIG = @"C:\Users\$username\Documents\c_projects\SeleniumScreenshots";
            private static string OUTPUT_FOLDER = @"C:\Users\$username\Documents\c_projects\pdf_output\";

            public static void Main(string[] args)
            {
                PdfDocument pdfDocument = new PdfDocument(new PdfWriter(OUTPUT_FOLDER + "ImageToPdf.pdf"));
                Document document = new Document(pdfDocument);

                ImageData imageData = ImageDataFactory.Create(ORIG);
                Image image = new Image(imageData);
                image.SetWidth(pdfDocument.GetDefaultPageSize().GetWidth() - 50);
                image.SetAutoScaleHeight(true);

                document.Add(image);
                pdfDocument.Close();
            }
        }
    }

When I run this, I am getting access denied to the SeleniumScreenshots folder, but the other folder (pdf_output) seems to have access. If i change the folder to the pdf_output folder to get the images from there, im still getting access denied, however, it is writing the empty pdf to the output folder so it seems to have access. I tried changing the folders from "Read only" attribute but its not saving for some reason, I dont think thats the issue cause ive written to my documents folder in other selenium or c# projects and havent had issues. My thoughts are that im using itext7 wrong.

The goal here is to get grab the PNGs in my SeleniumScreenshots folder and turn them into a PDF and drop in the pdf_outputs folder after running a selenium/nunit test(not seen in code).

After not being able to get it to work with my selenium/nunit project, I opened a new project and set up their code to work(console application) and still had the same results. Im stumped.

I am pretty new to c# and visual studio code/developement in general. Thanks for any help in advance.


Solution

  • According to the comment, the solution is as follows:

    1. ORIG is a file name at the end, you can’t refer to the folder.
    2. OUTPUT_FOLDER last refers to the space under the folder, you are missing \.

    There is no problem with the code itself.