How to open PDF with NuGet Code - Select.HtmlToPdf - c#

Here is my code and it works (I used NuGet package Select.HtmlToPdf. Document.Save saves the PDF instead I would like the PDF open for user to review (instead of saving in computer)
HtmlToPdf converter = new HtmlToPdf();
// create a new pdf document converting an url
PdfDocument doc = converter.ConvertUrl("www.cnn.com");
// save pdf document
doc.Save.(Response, false, "test.pdf"); // false: will not save the document
// close pdf document
doc.Close();

To open in browser, after PDFDocument initiated:
PdfDocument doc = converter.ConvertHtmlString("www.cnn.com");
byte[] bytes = doc.Save();
string mimeType = "Application/pdf";
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
Response.End();

Related

Display .jpg / .png image from folder in browser instead of downloading it ASP.NET

I am trying to display .png / .jpg image in browser but the problem is instead of displaying the image in the browser it is getting downloaded. I have tried using content-disposition:inline as well but its downloading the complete aspx page. Can anyone help me with this. Below is my code
string filePath = "C:\\inetpub\\wwwroot\\Folder\\OSP\\20139000\\";
string filename = "test.jpg";
string contenttype = "image/" +
Path.GetExtension(filename.Replace(".", ""));
FileStream fs = new FileStream(filePath + filename,
FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
////Write the file to response Stream
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contenttype;
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
You miss
Response.Clear();
somewhere at the beginning of the script. Without clearing the response's buffer first, it already contains the text of the *.aspx page the script is run under.
Then, don't set the content's disposition to attachment, completely delete this line.

Change download-file name ItextSharp

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

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

Exporting Grid Data to Excel and saving it in zip format

Hi i'm working on asp net application. In this I need to Export Grid data to Excel and finally the excel file should be saved as zip file. I don't want to first save Excel file in some location then use zip functionality to fetch that file and convert it into Zip and save it. I want functionality which will directly convert Grid to Excel then Zip then finally saves it. I've seen so many forms and sites but none gave proper answer.
You can do this by dot.net Zip dll And following code will help you
gv.AllowPaging = false;
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/zip";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
// byte[] toBytes = Encoding.ASCII.GetBytes(somestring);
MemoryStream stream = new MemoryStream();
string attachment = sw.ToString();
byte[] data = Encoding.ASCII.GetBytes(attachment);
stream.Write(data, 0, data.Length);
stream.Seek(0, SeekOrigin.Begin); // <-- must do this after writing the stream!
// File.WriteAllBytes(#"D:\Saurabh\Testing\inputpdf\saurabhhtest.xls", stream.GetBuffer());
using (ZipFile zipFile = new ZipFile())
{
zipFile.AddEntry("saurabhtest1.xls", stream);
zipFile.Save(Response.OutputStream);
}

Running out the PDF page while generating PDF using iTextSharp.dll

I am generating the PDF using iTextSharp.i have a HTMl Page and i am Reading HTML Page then generate the PDF.but the Problem is that the half of the page is in PDF while another half of the Page is running out the page in PDF.i mean half of the Page is displayed in PDF.while half of the Page is cutting in PDF.
my code is like this in Load Event..
string fileContents;
string FilePath = Server.MapPath("print-withoutlogin.html");
StreamReader mstrFileStreamReader = new StreamReader(FilePath);
try
{
fileContents = mstrFileStreamReader.ReadToEnd();
byte[] result = createPDF(fileContents.ToString()).GetBuffer();
Response.Clear();
Response.AddHeader("Content-Length", result.Length.ToString());
Response.ContentType = "application/pdf";
Response.AddHeader("Accept-Ranges", "bytes");
Response.Buffer = true;
Response.AddHeader("Expires", "0");
Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
Response.AddHeader("Pragma", "public");
Response.AddHeader("content-Transfer-Encoding", "binary");
Response.AddHeader("Content-Disposition", "attachment; filename=kartik.pdf");
Response.BinaryWrite(result);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
throw ex;
}
finally
{
mstrFileStreamReader.Close();
}
and
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
Document document = new Document(PageSize.A4, 0, 0, 50, 50);
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
HTMLWorker worker = new HTMLWorker(document);
//worker.SetStyleSheet(styles);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
Have you Considered using Crystal Reports? I find it much easier and you can use
pdfStream = (MemoryStream)report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

Categories