iTextSharp generate PDF and show it on the browser directly - asp.net

How to open the PDF file after created using iTextSharp on ASP.Net? I don't want to save it on the server, but directly when the new PDF is generated, it shows on the browser. Is it possible to do that?
Here is the example for what I mean: Click here . But on this example, the file directly downloaded.
How can I do that?
Dim doc1 = New Document()
'use a variable to let my code fit across the page...
Dim path As String = Server.MapPath("PDFs")
PdfWriter.GetInstance(doc1, New FileStream(path & "/Doc1.pdf", FileMode.Create))
doc1.Open()
doc1.Add(New Paragraph("My first PDF"))
doc1.Close()
The code above do save the PDF to the server.
Thank you very much in advance! :)

You need to set Content Type of the Response object and add the binary form of the pdf in the header
private void ReadPdfFile()
{
string path = #"C:\Somefile.pdf";
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length",buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}
(or) you can use System.IO.MemoryStream to read and display:
Here you can find that way of doing it
Open Generated pdf file through code directly without saving it onto the disk

The problem solved with the code below:
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim pdfDoc As New Document()
PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream)
pdfDoc.Open()
'WRITE PDF <<<<<<
pdfDoc.Add(New Paragraph("My first PDF"))
'END WRITE PDF >>>>>
pdfDoc.Close()
HttpContext.Current.Response.Write(pdfDoc)
HttpContext.Current.Response.End()
Hope help! :)

Related

Unable to open PDF after it's generated (vb.net) (asp.net)

Sorry for this question, but I'm new in .net and vb.net. I really need your help! I generate a PDF file in asp.net (vb.net). It should be opened in a browser automatically, but it gives an error - Failed to load PDF document. I see it's created on a drive and opens properly. What could be an issue?
Protected Sub ExportToPDF(sender As Object, e As EventArgs)
Response.ContentType = "application/pdf"
Dim pdfDoc As New Document(PageSize.A4, 50.0F, 10.0F, 10.0F, 10.0F)
PdfWriter.GetInstance(pdfDoc, New
FileStream(Context.Server.MapPath("~/ejik.pdf"), FileMode.CreateNew))
pdfDoc.Open()
pdfDoc.Add(New Paragraph("What is going on?"))
pdfDoc.Close()
Response.Write(pdfDoc)
Response.End()
End Sub
Thank you in advance!
P.S.: Sorry, I forgot to mention that I use iTextSharp to create a PDF
Your code is all wrong. You are creating a web application, and you create an object of type Document so that you can write a PDF file to disk. (Do you even need that file on disk? You are writing a web application!) Then, instead of sending the file to the end user, you write a Document object to the Response instead of (the bytes of) the file. That can never work, can it?
It would be better if you created the PDF file in memory first:
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(Assinatura());
document.Close();
Then you take the bytes of that file in memory, and send them to the Response:
byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=ejik.pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
This is what the comment meant. Instead of pdfDoc, you need to send the byte array of the PDF file. See also iTextSharp is producing a corrupt PDF with Response

set default name to PDF document with itextsharp

i am sending a PDF to my page and i want to set a default name when the user tries to save the PDF document.
i am using ItextSharp and VB.Net
Using s As MemoryStream = New MemoryStream()
Dim Pdf_Writer As PdfWriter = PdfWriter.GetInstance(DocumentPDF, s)
DocumentPDF.Open()
DocumentPDF.SetMargins(10.0F, 10.0F, 10.0F, 10.0F)
DocumentPDF.Add(Table)
DocumentPDF.Close()
contentX= s.ToArray()
HttpContext.Current.Response.Buffer = False
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ContentType = "Application/pdf"
HttpContext.Current.Response.BinaryWrite(contentX)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
End Using
.
Response.AddHeader("content-disposition", #"attachment;filename=""MyFile.pdf""");
this way download the file(yea, it sets a default name), but i just want to show the file and if the user wants to save it, well... save it(with a default name)
how can i set a default name to my PDF document?
try with this code:
Response.ContentType = "application/pdf"
Response.AppendHeader("Content-Disposition", "inline; filename="filename".pdf")
Response.TransmitFile("filename")
Response.End()
I had a similar problem delivering a PDF via a handler page (.ashx). No matter what I set in the HTTP headers, saving from the browser PDF reader would always set the filename to "getpdf.pdf" when I used this url.
http://www.thepdfchef.com/handlers/getpdf.ashx?id=5188p
So what I did was add an escaped string after the handler path then the querystring at the end of that, like so:
http://www.thepdfchef.com/handlers/getpdf.ashx/Wellbeing%20And%20Domestic%20Assistance%20From%20John%20Paul?id=5188p
You should check for invalid characters and strip out any that could cause the name to be dangerous.

asp.net openxml open docx, change content and stream to user

My code is below. I'm trying to open a Word document with Open XML and change certain text. The document must then be send to the client where they can save it on their PC or Open it. It send a document to the client but it is blank. When I save my InMemory document it says the file cannot be open it must contain at least one root element. I'm using Visual STudio 2010 Express. Please help me. What is wrong with my code?
Dim fileName As String = "directory on server\doc.docx"
Dim myDocument As WordprocessingDocument = WordprocessingDocument.Open(fileName, True)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(myDocument.MainDocumentPart.GetStream)
docText = sr.ReadToEnd
sr.Close()
Dim regexText As Regex = New Regex("XXXCourtXXX")
docText = regexText.Replace(docText, "JOHANNESBURG")
Dim ms As New MemoryStream()
Dim sw As StreamWriter = New StreamWriter(ms)
sw.Write(docText)
myDocument.MainDocumentPart.FeedData(ms)
Dim mem = New MemoryStream()
myDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream)
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Response.AppendHeader("Content-Disposition", "attachment;filename=Notice.docx")
mem.Position = 0
mem.CopyTo(Response.OutputStream)
Response.Flush()
Response.End()
You're dimming a new memory stream mem, writing nothing to it and then copying it to the output stream. Remove all lines referencing your mem variable.

What's the easiest way to convert a BMP to a PDF in ASP.net

What's the easiest way to convert a BMP file to a single page PDF using ASP.net? I'm going to generate the 8.5" x 11" BMP in Flash (which means I can manipulate it to make it as easy as possible), then use a POST to upload it to an ASP page, which will convert it to a PDF and redirect the user to the PDF. I don't want to add any margins or anything else, it will be laid out properly in the BMP for full-bleed.
Would it be easier to convert it to PDF in Flash, then upload?
Thanks!
You can use iTextSharp to create a PDF and insert the image into the document. This can be done all in memory with a final PDF produced to client.
The following is an MVC method, stripped for display, but should see how to do this.
[HttpGet]
public FileStreamResult Export(int? ID)
{
MemoryStream stream = new MemoryStream();
Document pdf = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdf, stream);
pdf.Open();
PdfPTable tblImage = new PdfPTable(1);
tblImage.AddCell(Image.GetInstance(LogChart())); //The LogChart method returns image
pdf.Add(Image);
pdf.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Log.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
}

ASP.NET page to image or PDF

I have an ASP.NET page like this:
http://farm4.static.flickr.com/3631/3690714302_c17b259863.jpg
My table is Gridview and some Label, anybody can tell me how to create a button to convert my page to image or PDF file and save it to desktop.
It can be done by code on the backend that renders the html into a memory Graphic object and then serves that resultant bitmap back, or by printing the page (on the server) through a PDF writer and then capturing the result.
Javascript, no.
Or google "online convert html pdf" and use one of those services.
Hai use iTextSharp to convert your webpage to pdf.
It looks very nice.
Just download the dll file and add reference to your application.
Then in button click give the coding as follows.
Response.ClearHeaders()
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", attachment; filename="jaison.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Me.Page.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(iTextSharp.text.PageSize.A2, 10, 10, 10, 10)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.End()
Surely this code will help you.
All the best!

Resources