I'm trying to generate a pdf file using itextsharp.
Here is the method that's supposed to generate the PDF:
private void Page_onPreRenderComplete(object sender, EventArgs e)
{
// createPdf.GeneratePDF(htmlMarkup);
MemoryStream memoryStream = new MemoryStream();
StringBuilder sBuilder = new StringBuilder();
StringWriter sw = new StringWriter(sBuilder);
HtmlTextWriter htmlText = new HtmlTextWriter(sw);
Page.RenderControl(htmlText);
string pdfBody = sBuilder.ToString();
Document document = new Document();
PdfWriter.GetInstance(document, memoryStream);
document.Open();
StyleSheet styles = new StyleSheet();
HTMLWorker hw = new HTMLWorker(document);
try
{
hw.Parse(new StringReader(pdfBody));
}
catch (Exception ex)
{
string msg = ex.Message;
}
finally
{
document.Close();
}
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.Write(memoryStream);
HttpContext.Current.Response.End();
}
an error is generated on the line within the try block. How can I fix this?
may be the image tags etc are in relative paths instead of absolute paths in the rendered HTML
Related
We are unable to change font size of pdf generated from below code anybody can help us?
We would like to convert that html file into pdf after changing the font size.
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
protected void ConvertToPDFNow()
{
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
print.RenderControl(w);
string htmWrite = sw.GetStringBuilder().ToString();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
htmWrite = Regex.Replace(htmWrite, "</?(a|A).*?>", "");
htmWrite = htmWrite.Replace("\r\n", "");
StringReader reader = new StringReader(htmWrite);
Document doc = new Document(PageSize.A4);
//Creating Document of A4 Size
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
try
{
//rendering Html File
parser.Parse(reader);
}
catch (Exception ex)
{
}
finally
{
doc.Close();
}
}
try to apply stylesheet:
...
var style = new StyleSheet();
style.LoadTagStyle("body", "size", "12px");
parser.SetStyleSheet(style);
...
The C# code below works fantastically to change itextpdf font size:
var style = new StyleSheet();
style.LoadTagStyle("body", "size", "8px");
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.SetStyleSheet(style);
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);
}
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);
var htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), styles);
document.Open();
BaseFont Vn_Helvetica = BaseFont.CreateFont(#"C:\Windows\Fonts\arial.ttf",
"Identity-H", BaseFont.EMBEDDED);
Font fontNormal = new Font(Vn_Helvetica, 12, Font.NORMAL);
foreach (var t in htmlarraylist)
{
if (t is PdfPTable)
{
//how set fontNormal all text from Pdfptable ?
}
document.Add((IElement)t);
}
document.Close();
Can someone help me please
Please try by setting font to the PdfPTable.DefaultCell property in you foreach loop
Example:
t.DefaultCell.Phrase = new Phrase() { Font = fontNormal };
i have try set font family in pdf template. and show the following error also
'BaseFont' does not contain a definition for 'Cambria'
please suggest me...thanks
public void abcd()
{
try
{
string UniqueNumber = Request.QueryString["UniqueNumber"];
string strFileName = UniqueNumber;
string strFileExtension = ".pdf";
string strContentType = FileManager.FileContentType_application_pdf;
string strExportData = string.Empty;
Document pdfDoc = new Document();
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
var output = new MemoryStream();
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.Cambria, BaseFont.CP1252, false);
//Font ChronicleFont = new Font(bfTimes, 26f);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
StringReader sr;
sr = new StringReader(Convert.ToString(ExportData.UserDetails(UniqueNumber)));
PdfWriter.GetInstance(pdfDoc, output);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
strFileName = strFileName.Replace(" - ", "-").Replace(" ", "-").Replace("--", "-");
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}{1}", strFileName, strFileExtension));
Response.ContentType = strContentType;
Response.Charset = "";
Response.BinaryWrite(output.ToArray());
Response.Flush();
Response.End();
}
catch (Exception ex)
{
//
}
}
I have use ItextSharp to generate pdf file from an aspx page.
But it gives me an error in an obj.Parse(se), where se is the string reader and it takes the path of:-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
I am stuck with this problem.
Please help and give suggesstion.
Thank You
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.Xml;
using iTextSharp.text.html.simpleparser;
public partial class Pdf : System.Web.UI.Page
{
protected override void Render(HtmlTextWriter writer)
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
base.Render(myWriter);
myWriter.Flush();
myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
strmRdr.Dispose();
mem.Dispose();
writer.Write(pageContent);
CreatePDFDocument(pageContent);
}
public void CreatePDFDocument(string strHtml)
{
string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
document.Close();
ShowPdf(strFileName);
}
public void ShowPdf(string strFileName)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.ContentType = "application/pdf";
Response.WriteFile(strFileName);
Response.Flush();
Response.Clear();
}
}
Here is an example that worked for me. There is a bit of code but it shows ways you can take advantage of things like css. Hope it helps.
private void ExportToPDF()
{
string s = "<table><td><tr>First<b>row</b></tr></td></table>";
Document document = new Document(PageSize.LETTER, 30, 30, 60, 35);
MemoryStream msReport = new MemoryStream();
string strHTMLpath = Server.MapPath("../myHTML.html");
string strPDFpath = Server.MapPath("../myPDF.pdf");
try
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
StreamWriter strWriter = new StreamWriter(strHTMLpath, false, Encoding.UTF8);
strWriter.Write(s.ToString());
strWriter.Close();
strWriter.Dispose();
iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle("ol", "leading", "16,0");
PdfWriter.GetInstance(document, new FileStream(strPDFpath, FileMode.Create));
document.Add(new Header(iTextSharp.text.html.Markup.HTML_ATTR_STYLESHEET, "Style.css"));
document.Open();
ArrayList objects;
styles.LoadTagStyle("li", "face", "garamond");
styles.LoadTagStyle("span", "size", "8px");
styles.LoadTagStyle("body", "font-family", "times new roman");
styles.LoadTagStyle("body", "font-size", "10px");
document.NewPage();
objects = iTextSharp.text.html.simpleparser.
HTMLWorker.ParseToList(new StreamReader(strHTMLpath, Encoding.Default), styles);
for (int k = 0; k < objects.Count; k++)
{
document.Add((IElement)objects[k]);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
document.Close();
Response.Write(strPDFpath);
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=myFileName.pdf");
Response.ContentType = "application/octet-stream";
Response.WriteFile(strPDFpath);
Response.Flush();
Response.Close();
File.Delete(strPDFpath);
}
}