Con*_*ole 8 printing asp.net web-applications itext itextsharp
如何从Web应用程序生成纸质打印?
具体来说,我正在考虑更复杂的纸质文件,如文凭,发票和合同.包含框架,表格,徽标和页眉/页脚的可变页数.
今天我使用自定义表单和CSS用于某些事情,iTextSharp用于其他人(我使用asp.net和MS-SQL),但我认为这两种方法都非常耗时且很难在不同文档中保持一致.
还有更好的方法吗?
使用 iTextSharp 从头开始创建文档可能非常耗时。作为替代方案,您可以通过向 PDF“模板”文档添加表单字段(如有必要)来创建(或重用)PDF“模板”文档。最简单的方法是使用完整版的 Adobe Acrobat,但您也可以只使用 iTextSharp 添加可填写的表单字段。
例如,对于奖项或文凭,您可以查找、创建或修改包含文档的所有文本、图形、精美边框和字体的 PDF,然后添加收件人姓名的表单字段。您可以添加日期、签名行、奖励类型等其他字段。
然后,可以非常轻松地从 Web 应用程序使用 iTextSharp 来填写表单、展平表单并将其流式传输回用户。
本文末尾是完整的 ASHX 处理程序代码示例。
另请记住,iTextSharp(或只是 iText)对于组合 PDF 文档或不同文档的页面也很有用。因此,对于封面或说明页固定设计但动态生成内容的年报,您可以打开封面页,打开报告的模板页面,将动态内容生成到模板的空白区域,打开背面页面“样板”,然后将它们全部组合成一个文档以返回给用户。
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Text;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace iTextFormFillerDemo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class DemoForm : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/pdf";
//This line will force the user to either open or save the
//file instead of it appearing on its own page - if you remove it,
//the page will appear in the browser in the same window.
context.Response.AddHeader("Content-Disposition",
"attachment; filename=DemoForm_Filled.pdf");
FillForm(context.Response.OutputStream);
context.Response.End();
}
// Fills the form and pushes it out the output stream.
private void FillForm(System.IO.Stream outputStream)
{
//Need to get the proper directory (dynamic path) for this file.
//This is a filesystem reference, not a web/URL reference...
//The PDF reader reads in the fillable form
PdfReader reader = new PdfReader("C:/DemoForm_Fillable.pdf");
//The PDF stamper creates an editable working copy of the form from the reader
//and associates it with the response output stream
PdfStamper stamper = new PdfStamper(reader, outputStream);
//The PDF has a single "form" consisting of AcroFields
//Note that this is shorthand for writing out
//stamper.AcroFields.SetField(...) for each set
AcroFields form = stamper.AcroFields;
//Set each of the text fields this way: SetField(name, value)
form.SetField("txtFieldName", "Field Value");
form.SetField("txtAnotherFieldName", "AnotherField Value");
//Set the radio button fields using the names and string values:
form.SetField("rbRadioButtons", "Yes"); //or "No"
//Form flattening makes the form non-editable and saveable with the
//form data filled in
stamper.FormFlattening = true;
//Closing the stamper flushes it out the output stream
stamper.Close();
//We're done reading the file
reader.Close();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4708 次 |
| 最近记录: |