Curious-programmer
Curious-programmer

Reputation: 813

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

I get an error

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

Upvotes: 1

Views: 640

Answers (2)

Janley Zhang
Janley Zhang

Reputation: 1587

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

Upvotes: 1

Fabrizio Accatino
Fabrizio Accatino

Reputation: 2302

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);

Upvotes: 1

Related Questions