C# iTextSharp从一页模板高效批量生成Pdf
我正在使用ITextSharp生成一个多页PDF,每个页面都有sames模板 问题是PDF的物理大小随着模板的大小而增长 我有使用ACROFIELDS 如何减小最终文件大小 以下是pdf处理程序的代码片段:C# iTextSharp从一页模板高效批量生成Pdf,c#,asp.net,pdf-generation,itextsharp,C#,Asp.net,Pdf Generation,Itextsharp,我正在使用ITextSharp生成一个多页PDF,每个页面都有sames模板 问题是PDF的物理大小随着模板的大小而增长 我有使用ACROFIELDS 如何减小最终文件大小 以下是pdf处理程序的代码片段: public void ProcessRequest(HttpContext context) { Context = context; Response = context.Response; Request = context.Request; try
public void ProcessRequest(HttpContext context)
{
Context = context;
Response = context.Response;
Request = context.Request;
try
{
LoadDataInternal();
}
catch (System.Threading.ThreadAbortException)
{
// no-op
}
catch (Exception ex)
{
Logger.LogError(ex);
Response.Write("Error");
Response.End();
}
Response.BufferOutput = true;
Response.ClearHeaders();
Response.ContentType = "application/pdf";
if (true)
{
Response.AddHeader("Content-Disposition", "attachment; filename=" +
(string.IsNullOrEmpty(DownloadFileName) ? context.Session.SessionID + ".pdf" : DownloadFileName));
}
PdfCopyFields copy
= new PdfCopyFields(Response.OutputStream);
// add a document
for (int i = 0; i < dataset.Tables["Model"].Rows.Count; i++)
{
copy.AddDocument(new PdfReader(renameFieldsIn(TemplatePath, i)));
// add a document
}
copy.SetFullCompression();
// Close the PdfCopyFields object
copy.Close();
}
private byte[] renameFieldsIn(String datasheet, int i)
{
MemoryStream baos = new MemoryStream();
// Create the stamper
PdfStamper stamper = new PdfStamper(new PdfReader(GetTemplateBytes()), baos);
// Get the fields
AcroFields form = stamper.AcroFields;
// Loop over the fields
List<String> keys = new List<String>(form.Fields.Keys);
foreach (var key in keys)
{
// rename the fields
form.RenameField(key, String.Format("{0}_{1}", key, i));
}
stamper.FormFlattening = true;
stamper.FreeTextFlattening = true;
stamper.SetFullCompression();
SetFieldsInternal(form, i);
// close the stamper
stamper.Close();
return baos.ToArray();
}
protected byte[] GetTemplateBytes()
{
var data = Context.Cache[PdfTemplateCacheKey] as byte[];
if (data == null)
{
data = File.ReadAllBytes(Context.Server.MapPath(TemplatePath));
Context.Cache.Insert(PdfTemplateCacheKey, data,
null, DateTime.Now.Add(PdfTemplateCacheDuration), Cache.NoSlidingExpiration);
}
return data;
}
public void ProcessRequest(HttpContext上下文)
{
上下文=上下文;
Response=context.Response;
Request=context.Request;
尝试
{
LoadDataInternal();
}
catch(System.Threading.ThreadAbortException)
{
//无操作
}
捕获(例外情况除外)
{
Logger.LogError(ex);
响应。写入(“错误”);
Response.End();
}
Response.BufferOutput=true;
Response.ClearHeaders();
Response.ContentType=“application/pdf”;
如果(真)
{
AddHeader(“内容处置”、“附件;文件名=”+
(string.IsNullOrEmpty(DownloadFileName)?context.Session.SessionID+“.pdf”:DownloadFileName));
}
PdfCopyFields副本
=新的PdfCopyFields(Response.OutputStream);
//添加文档
对于(int i=0;i
我以前做过一些类似的事情,发现在合并所有页面后,通过PDFStamper再次运行整个生成的文档会导致文件大小明显压缩。好的,所以我的一个朋友想出了一个解决方案。剩下的唯一问题是创建新PdfStamper所需的内存量。这是重写的过程
无论如何。希望这会让其他人失望。如果你有更好的解决方案,请不要害羞
public void ProcessRequest (HttpContext context)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
Context = context;
Response = context.Response;
Request = context.Request;
Response.BufferOutput = true;
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=itextsharp_multiple.pdf");
var pageBytes = (byte[])null;
var pagesAll = new List<byte[]>();
try
{
for (int i = 0; i < GlobalHttpApplication.Model.TestData.Rows.Count; i++)
{
PdfStamper pst = null;
MemoryStream mstr = null;
using (mstr = new MemoryStream())
{
try
{
PdfReader reader = new PdfReader(GetTemplateBytes());
pst = new PdfStamper(reader, mstr);
var acroFields = pst.AcroFields;
SetFieldsInternal(acroFields, 0);
pst.FormFlattening = true;
pst.SetFullCompression();
} finally
{
if (pst != null)
pst.Close();
}
}
pageBytes = mstr.ToArray();
pagesAll.Add(pageBytes);
}
} finally
{
}
Document doc = new Document(PageSize.A4);
var writer = PdfWriter.GetInstance(doc, Response.OutputStream);
var copy2 = new PdfSmartCopy(doc, Response.OutputStream);
doc.Open();
doc.OpenDocument();
foreach (var b in pagesAll)
{
doc.NewPage();
copy2.AddPage(copy2.GetImportedPage(new PdfReader(b), 1));
}
copy2.Close();
watch.Stop();
File.AppendAllText(context.Server.MapPath("~/App_Data/log.txt"), watch.Elapsed + Environment.NewLine);
}
public void ProcessRequest(HttpContext上下文)
{
var watch=System.Diagnostics.Stopwatch.StartNew();
上下文=上下文;
Response=context.Response;
Request=context.Request;
Response.BufferOutput=true;
Response.ClearHeaders();
Response.ContentType=“application/pdf”;
AddHeader(“内容处置”、“附件;文件名=itextsharp_multiple.pdf”);
var pageBytes=(byte[])null;
var pagesAll=新列表();
尝试
{
对于(int i=0;i