How to Change Default Font Size in iTextSharp After Exporting GridView to PDF?

左心房为你撑大大i 提交于 2019-12-12 11:13:46

问题


I am using the iTextSharp method in the following link to export a GridView to a PDF document:

http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx

The code is like this:

protected void btnExportPDF_Click(object sender, EventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;
    GridView1.DataBind(); 
    GridView1.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f,10f,10f,0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();

    Response.Write(pdfDoc);
    Response.End();  
}

This works perfect except the font size in the PDF. I guess the defaults for iTextSharp are Arial and 12pt.

Is there any way to change this default font and its size (at least its size) globally for the whole PDF?

Thank you!


回答1:


There is indeed.

(but my initial suggestion isn't it... Font.DEFFAULTSIZE is "static final", so... Derp).

Err... I don't think HTMLWorker's stylesheet code will let you set an overall default font size, thought I haven't worked with it all that much. I could be wrong. You can set it by class or tag, but that could be quite a bit of work... hey!

I think you can set the style for "body" which will then affect everything within it. Unless you're working on HTML fragments, this should do the trick:

StyleSheet bodySize = new StyleSheet();
Map<String,String> props = new HashMap<String, String>();
props.put(ElementTags.SIZE, "8"); 
bodySize.applyStyle("body", props);

htmlparser.setStyleSheet(bodySize);

The way I did it was Change The Source (com.itextpdf.text.Font.java) so that the declaration of Font.DEFAULTSIZE was to my liking, but I maintain my own branch... I'm weird like that.




回答2:


BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font font20 = iTextSharp.text.FontFactory.GetFont
(iTextSharp.text.FontFactory.HELVETICA,20);



回答3:


C#

Hashtable props = new Hashtable();
props.Add(ElementTags.SIZE, "8");


来源:https://stackoverflow.com/questions/6349847/how-to-change-default-font-size-in-itextsharp-after-exporting-gridview-to-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!