1

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"));
document.Close();

I get an error

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

Leonardo Henriques
  • 784
  • 1
  • 7
  • 22
Curious-programmer
  • 772
  • 3
  • 13
  • 31

2 Answers2

1

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

Document document = new Document(PageSize.A4);
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.NewPage();
...
...
document.Close();

Response.Clear();
Response.ContentType = "application/pdf";
byte[] pdfBytes = ms.ToArray();
Response.AppendHeader("Content-Length", pdfBytes.Length.ToString());
Response.OutputStream.Write(pdfBytes, 0, (int)pdfBytes.Length);
Fabrizio Accatino
  • 2,284
  • 20
  • 24
  • After Mkl's suggestion I found essentially the same solution (https://stackoverflow.com/questions/1196059/itextsharp-sending-in-memory-pdf-in-an-email-attachment?rq=1), without the last half . – Curious-programmer Mar 14 '18 at 14:43
  • 1
    @Curious in that case please either accept this answer (as it's similar enough) or create your own answer to eventually accept. – mkl Mar 14 '18 at 21:28
1

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.Open();
        doc.Add(new Paragraph("Hello World")); //change content in pdf
        doc.Close();
    

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

enter image description here

Janley Zhang
  • 1,567
  • 7
  • 11