How to store Generated pdf on deployed website with Itext

I am trying to write to a pdf and send it in an email.I am able to implement this on my local machine. The problem is when I deploy to azure I am not sure where to store the pdf . I have seen one question regarding this and tried this solution from stackoverflow - Does iText (any version) work on Windows Azure websites?.

var path = Server.MapPath("test.pdf");

FileInfo dest = new FileInfo(path);

var writer = new PdfWriter(dest);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("hello world"));

I get an error

Could not find a part of the path 'D:\home\site\wwwroot\Email\test.pdf'.

2 answers

  • answered 2018-03-14 07:42 Fabrizio Accatino

    Try to create the Pdf in memory and stream the content to the output stream.

    Document document = new Document(PageSize.A4);
    MemoryStream ms = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(document, ms);
    Response.ContentType = "application/pdf";
    byte[] pdfBytes = ms.ToArray();
    Response.AppendHeader("Content-Length", pdfBytes.Length.ToString());
    Response.OutputStream.Write(pdfBytes, 0, (int)pdfBytes.Length);

  • answered 2018-03-14 07:47 Janley Zhang

    I suppose your issue is related with the file path. If I use the path like Server.MapPath("Azure_Example1.pdf"), I also get the same error as you.

    enter image description here

    I suggest you could try to use the relative path like Server.MapPath("~/Azure_Example1.pdf"). The '~/' points to the project root directory.

    You could also set a break point to check the value of path by using remote debugging.

    enter image description here

    I have created a simple demo, it works fine on my side. You could refer to.

    1. Install the iTextSharp 5.5.13 nuget package in Manage Nuget Packages.

    2. Use the following code:

          var path = Server.MapPath("~/Azure_Example1.pdf");
          FileInfo dest = new FileInfo(path);
          FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
          Document doc = new Document();
          PdfWriter writer = PdfWriter.GetInstance(doc, fs);
          doc.Add(new Paragraph("Hello World")); //change content in pdf

    Finally, you could see the pdf file has been stored in root project directory.

    enter image description here