如何在将GridView导出为PDF后更改iTextSharp中的默认字体大小?

nca*_*mak 5 pdf asp.net gridview export itextsharp

我在以下链接中使用iTextSharp方法将GridView导出为PDF文档:

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

代码是这样的:

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();  
}
Run Code Online (Sandbox Code Playgroud)

除了PDF中的字体大小外,这种方法很完美.我想iTextSharp的默认值是Arial和12pt.

有没有办法在整个PDF中全局更改此默认字体及其大小(至少是其大小)?

谢谢!

Mar*_*rer 0

确实有。

(但我最初的建议不是...... Font.DEFFAULTSIZE 是“静态最终”,所以...... Derp)。

呃...我认为 HTMLWorker 的样式表代码不会让您设置整体默认字体大小,虽然我还没有使用它那么多。我可能是错的。您可以通过类或标签来设置它,但这可能是一项相当大的工作......嘿!

我认为你可以设置“body”的样式,这将影响其中的所有内容。除非您正在处理 HTML 片段,否则这应该可以解决问题:

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

htmlparser.setStyleSheet(bodySize);
Run Code Online (Sandbox Code Playgroud)

我这样做的方式是更改源(com.itextpdf.text.Font.java),以便声明Font.DEFAULTSIZE符合我的喜好,但我维护自己的分支......我很奇怪。