Set font for all text from Pdfptable with Itextsharp - c#

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)
{
//
}
}

Related

Value cannot be null. Parameter name: elementId in PDFsharp

I am working on Export to PDF funtionality using C# and PDFSharp. I am getting this error:
Value cannot be null.
Parameter name: elementId
The error is on this line :
PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4, 30);
Here's the whole method:
public bool ExportPdf(string htmlcontenttbl)
{
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=Myfile.pdf");
//Response.AddHeader("Content-Disposition", "inline;filename=file.pdf");
//Response.AppendHeader("Content-Disposition", "attachment; filename=Myfile.pdf");
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4, 30);
var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.PageSize = PageSize.A4;
config.MarginBottom = 30;
config.MarginTop = 30;
//PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl, config);
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
document.Save(stream, true);
bytes = stream.ToArray();
}
//var path1 = Server.MapPath("~/Images/" + DateTime.Now.TimeOfDay.Ticks + "result.pdf");
//System.IO.File.WriteAllBytes(path1, bytes);
//Response.TransmitFile(path1, 0, bytes.Length);
//Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return true;
}
That exception can occur if you have a blank anchor tag.
It is likely ultimately being generated from here.
You should remove the blank anchor tag.

Getting the error message: “Could not find a part of the path"

I create a Folder (File) and i want that after i click the button (btnGenerate_Click) it should create a pdf file and save it into the Folder, named "File". But i constantly getting the error message: "Could not find a part of the path "C:\User\VS\Intra\Intra.Admin\File\" But the Location of the path is correct....
protected void btnGenerate_Click(object sender, EventArgs e)
{
string FilePath = MapPath("~/File/"); //here!
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 20f, 20f, 20f, 20f);
PdfWriter.GetInstance(pdfDoc, new FileStream(FilePath, FileMode.Create));
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.HeaderRow.Cells[1].Text = "Message";
GridView1.HeaderRow.Font.Bold = true;
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.ContentType = "Application/pdf";
Response.WriteFile(FilePath);
Response.End();
}
FilePath is a directory. You should append a filename, so something like this:
string FilePath = MapPath("~/File/" + fileName);

Dynamically creating a grid view in pdf using itextsharp

protected void ExportToPdf(DataTable dt, string str)
{
ArrayList ADA = new ArrayList();
ADA.Add(FirstAssignment.SelectedItem);
ADA.Add(SecondAssignment.SelectedItem);
GridView GridView1 = new GridView();
GridView GridView2 = new GridView();
GridView1.ShowHeaderWhenEmpty = true;
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
int i1 = GridView1.Columns.Count;
GridView1.HeaderRow.Cells[1].Text = ADA[0].ToString();
GridView1.HeaderRow.Cells[2].Text = ADA[1].ToString();
GridView1.HeaderRow.Cells[3].Text = "% of Improvement from " + (ADA[0].ToString()) + " to " + (ADA[1].ToString());
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + str + ".pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.HeaderRow.ForeColor = System.Drawing.Color.Black;
GridView1.FooterRow.ForeColor = System.Drawing.Color.Black;
GridView1.HeaderRow.Style.Add("font-Color", "Black");
GridView1.HeaderRow.Style.Add("font-size", "13px");
GridView1.HeaderRow.Style.Add("text-decoration", "none");
GridView1.HeaderRow.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
GridView1.Style.Add("font-Color", "Black");
GridView1.Style.Add("text-decoration", "none");
GridView1.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
GridView1.Style.Add("font-size", "11px");
GridView1.ForeColor = System.Drawing.Color.Black;
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
// HTMLWorker htmlparser1 = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
pdfDoc.Add(new Paragraph("hey! rashmi"));
htmlparser.Parse(sr);
pdfDoc.Close();
HttpContext.Current.Response.Write(pdfDoc);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
This is for creating one grid view. can any one help me to create a dynamic grid view using this code.I have tried to giving a for loop GridView1.RenderControl(hw); but I am getting single grid view with same data.Thanks in advance.
If you want show gridview in pdf,you can show as table also here is
code :
public void createPdf()
{
// step 1
using (MemoryStream ms = new MemoryStream())
{
Document document = new Document(iTextSharp.text.PageSize.A4, 10, 22, 34, 34);
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// step 3
document.Open();
MemoryStream stream = new MemoryStream();
// step 4 how many tables you want to create
for (int i = 0; i < 5; i++)
{
document.Add(new Paragraph("Table:"));
document.Add(createFirstTable());
}
// step 5
document.Close();
writer.Close();
Response.ContentType = "pdf/application";
Response.AddHeader("content-disposition",
"attachment;filename=First PDF document.pdf");
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
}
public static PdfPTable createFirstTable(DataTable dt)
{
// a table with three columns
PdfPTable table = new PdfPTable(dt.Columns.Count);
// the cell object
PdfPCell cell;
// we add a cell with colspan 3
//cell = new PdfPCell(new Phrase("Cell with colspan 3"));
table.AddCell(cell);
//// now we add a cell with rowspan 2
cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
table.AddCell("ADXHGS");
table.AddCell("WFEWSA");
table.AddCell("EWSFCEDSW");
table.AddCell("EWSEWSFDFCEDSW");
//PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
return table;
}

Generating PDF using itestsharp

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

iTextSharp.HTMLWorker bad convert html encrypt UTF-8

I'd like to apologize, my English is not very good. I hope that you help me. I have this string from xslt trans.:
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<html>\r\n <head />\r\n <body style=\"font-family: Verdana, sans-serif;\">\r\n ĚŠČŘŽŘÝŽÝÁÁÍÉŮ ěščřžýáíéůú\r\n </body>\r\n</html>"
and when I trying convert this html string to pdf:
private static byte[] CreatePdfUsingXslt(string htmlText)
{
var msOutput = new MemoryStream();
var reader = new StringReader(htmlText);
var document = new Document(PageSize.A4, 30, 30, 30, 30);
var pdfWriter = PdfWriter.GetInstance(document, msOutput);
var worker = new HTMLWorker(document);
document.Open();
worker.StartDocument();
worker.Parse(reader);
worker.EndDocument();
worker.Close();
document.Close();
return msOutput.GetBuffer();
}
protected void SavePDF(byte[] storeData, string fileName)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.ContentType = "application/pdf";
Response.Charset = Encoding.UTF8.ToString();
Response.ContentEncoding = Encoding.UTF8;
Response.Buffer = true;
Response.BinaryWrite(storeData);
Response.Flush();
Response.End();
}
I'm getting something like this: ŠŽÝŽÝÁÁÍÉ šžýáíéú and it's wrong... My result doesn't have characters like Ě,Č,Ř,Ů,... These are czech language characters.
I try to use XMLParser like this:
private static byte[] CreatePdfUsingXslt(string htmlText, string serverPath)
{
var msInput = new MemoryStream(Encoding.UTF8.GetBytes(htmlText));
var msOutput = new MemoryStream();
msInput.Position = 0;
msOutput.Position = 0;
var doc = new Document(PageSize.A4, 30, 30, 30, 30);
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, msOutput);
var htmlPipelineContext = new HtmlPipelineContext();
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
var cssPath = String.Format("{0}XsltTemplates\\print.css", serverPath);
cssResolver.AddCssFile(cssPath,true);
var pipeline = new CssResolverPipeline(cssResolver,
new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(doc, pdfWriter)));
var xmlWorker = new XMLWorker(pipeline, true);
var xmlParser = new XMLParser(true, xmlWorker);
xmlParser.Parse(new StreamReader(msInput, Encoding.UTF8));
xmlParser.Flush();
doc.Close();
return msOutput.ToArray();
}
but function xmlParser.Parse(new StreamReader(msInput, Encoding.UTF8)); throw NullReferenceException.
This is more important for me. Do you have anyone any idea, how I fix it?

Categories