Change download-file name ItextSharp - c#

So I've been using itextsharp to create and download a file to the client. The PDF is created, but is created using the wrong file extension. It is downloaded as "webform1.aspx" But if I change the file extension it is correct. I need to learn how to change the file name when downloading using the memory stream, or a different method if needed. Code below, it is executed via a button on a blank webform.
protected void Button1_Click(object sender, EventArgs e)
{
// Create a Document object
Document document = new Document(PageSize.A4, 50, 50, 25, 25);
// Create a new PdfWriter object, specifying the output stream
MemoryStream output = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, output);
// Open the Document for writing
document.Open();
// Create a new Paragraph object with the text, "Hello, World!"
var welcomeParagraph = new Paragraph("Hello, World!");
// Add the Paragraph object to the document
document.Add(welcomeParagraph);
document.Close();
Response.ContentType = "pdf/application";
Response.BinaryWrite(output.ToArray());
}

You can add a content-disposition header with filename to Response object
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);

Related

ITextSharp Error - The document has no pages

I new in using ITextSharp and want create a simple pdf file. And I trying in localhost, it work fine but put in server it fail to create and show the error message " The document has no pages.". I got try find the solution in web but still the same. How to solve this kind of problem?
Below is my coding.
var html = GenerateHTML(lst, getuser);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Commision_" + name + "_" + DateTime.Now.ToString("yyyyMM") + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Render PlaceHolder to temporary stream
StringReader reader = new StringReader(html);
//Create PDF document
Document doc = new Document(PageSize.A4);
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
try
{
doc.NewPage();
parser.Parse(reader);
}
catch (Exception )
{
}
finally
{
doc.Close();
}
I guess you missed the following 2 lines after doc.close
Response.Write(doc);
Response.End();

Using ITextSharp creates PDF successfully but difficult to open downloaded PDF

I already generate a pdf using itextsharp..and save it in our local server. I want to download this pdf in another button click. Code for generate pdf is working properly.Downloading occured but some error ocuured trying to open it."Because it is either not a supportive file type,or file has been damaged
protected void createpdf_Click(object sender, EventArgs e)
{
fs = new FileStream(Server.MapPath("pdf") + "\\" + "First PDF document.pdf", FileMode.Create);
document = new Document(PageSize.A4, 25, 25, 30, 30);
writer = PdfWriter.GetInstance(document, fs);
document.Open();
document.Add(new Paragraph("Pdf Geneartion!"));
document.Close();
writer.Close();
fs.Close();
}
Code for download pdf
protected void download_Click(object sender, EventArgs e)
{
try
{
fs = new FileStream(Server.MapPath("pdf") + "\\" + "FirstPDFdocument1.pdf", FileMode.Create);
document = new Document(PageSize.A4, 25, 25, 30, 30);
writer = PdfWriter.GetInstance(document, fs);
using (MemoryStream ms = new MemoryStream())
{
document.Open();
Response.Clear();
Response.ContentType = "pdf/application";
Response.AddHeader("content-disposition", "attachment;filename=PDFdocument1.pdf");
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
writer.Close();
fs.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Everything looks more or less correct except the ContentType. It should be application/pdf instead of pdf/application. Also, as #lc points out, the MemoryStream does not look like it is being written to. Try something like this instead:
using (MemoryStream ms = new MemoryStream())
{
PdfWriter.GetInstance(document, ms); // added
document.Open();
Response.Clear();
Response.ContentType = "application/pdf"; // changed
Response.AddHeader("content-disposition", "attachment;filename=PDFdocument1.pdf");
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}

How to email a PDF without opening it

I have this code that creates a PDF file and then emails it. However, when I run it, it opens and will change my entire page to PDF. How can I stop the page to open the PDF?
PdfWriter.GetInstance(document, Response.OutputStream);
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
HTMLWorker htmlparser = new HTMLWorker(document);
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
document.Add(mainTable);
Response.Write(document);
writer.CloseStream = false;
document.Close();
memoryStream.Position = 0;
EmailPresenter.SkyMail asd = new EmailPresenter.SkyMail();
asd.SendMail("test#test.com", "This is a test email...", memoryStream, "Test.pdf");
Response.End();
I do not know this PdfWriter library. But my suggestion would be to not provide the Response.OutputStream to the PdfWriter.
Simply delete the first three lines and the Response stream will remain untouched. You might also want to remove the last line with the Response.End() method call.

generate pdf report on button click

i just want to see all the report on a pdf format on button click.
i use ...
protected void Button1_Click(object sender, EventArgs e)
{
//Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
//Write some content
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
// Now add the above created text using different class object to our pdf document
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
doc.Close(); //Close document
}
but not effective
Your button click is simply creating a document in memory, writing to it and closing it.
You need to output the document to the Response.Output stream.
This works for me:
protected void PrintButton_Click(object sender, EventArgs e)
{
if (!Page.IsValid) return;
Response.ContentType = "application/pdf";
using (var document = new Document())
{
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
document.Add(new Paragraph("Hello PDF!"));
document.Close();
}
}
The main thing that you were missing was the PdfWriter which writes the document to the Response.OutputStream

Create PDF in memory instead of physical file

How do one create PDF in memorystream instead of physical file using itextsharp.
The code below is creating actual pdf file.
Instead how can I create a byte[] and store it in the byte[] so that I can return it through a function
using iTextSharp.text;
using iTextSharp.text.pdf;
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("c:\\Test11.pdf", FileMode.Create));
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
doc.Close(); //Close document
Switch the filestream with a memorystream.
MemoryStream memStream = new MemoryStream();
PdfWriter wri = PdfWriter.GetInstance(doc, memStream);
...
return memStream.ToArray();
using iTextSharp.text;
using iTextSharp.text.pdf;
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
byte[] pdfBytes;
using(var mem = new MemoryStream())
{
using(PdfWriter wri = PdfWriter.GetInstance(doc, mem))
{
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
}
pdfBytes = mem.ToArray();
}
I've never used iTextPDF before but it sounded interesting so I took upon the challenge and did some research on my own. Here's how to stream the PDF document via memory.
protected void Page_Load(object sender, EventArgs e)
{
ShowPdf(CreatePDF2());
}
private byte[] CreatePDF2()
{
Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
using (MemoryStream output = new MemoryStream())
{
PdfWriter wri = PdfWriter.GetInstance(doc, output);
doc.Open();
Paragraph header = new Paragraph("My Document") {Alignment = Element.ALIGN_CENTER};
Paragraph paragraph = new Paragraph("Testing the iText pdf.");
Phrase phrase = new Phrase("This is a phrase but testing some formatting also. \nNew line here.");
Chunk chunk = new Chunk("This is a chunk.");
doc.Add(header);
doc.Add(paragraph);
doc.Add(phrase);
doc.Add(chunk);
doc.Close();
return output.ToArray();
}
}
private void ShowPdf(byte[] strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);
Response.BinaryWrite(strS);
Response.End();
Response.Flush();
Response.Clear();
}
Where your code has new FileStream, pass in a MemoryStream you've already created. (Don't just create it inline in the call to PdfWriter.GetInstance - you'll want to be able to refer to it later.)
Then call ToArray() on the MemoryStream when you've finished writing to it to get a byte[]:
using (MemoryStream output = new MemoryStream())
{
PdfWriter wri = PdfWriter.GetInstance(doc, output);
// Write to document
// ...
return output.ToArray();
}
I haven't used iTextSharp, but I suspect some of these types implement IDisposable - in which case you should be creating them in using statements too.

Categories