iText C# 合并PDF文件流,以及A5变A4时内容默认放在最底下的问题的解决方法;ASP.NET 实现Base64文件流下载PDF

时间:2023-12-09 21:16:49
/// <summary> 合併PDF檔(集合) </summary>
/// <param name="files">欲合併PDF檔之集合(一筆以上)</param>
/// <param name="pagesize">纸张大小</param>
public static MemoryStream mergePDFStream(MemoryStream[] files, Rectangle pagesize = null)
{
//outMergeFile = Server.MapPath(outMergeFile);
//if (outMergeFile == null)
//{
// outMergeFile = "d:\\" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + new Random().Next(1000) + ".pdf";
//}
PdfReader reader;
Document document;
if (pagesize == null)
{
pagesize = PageSize.A4;
} document = new Document(pagesize);
//var fs = new FileStream(outMergeFile, FileMode.Create);
MemoryStream fs = new MemoryStream();
//BufferedStream bfs = new BufferedStream(fs);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
writer.CloseStream = false; //不自动关闭内存流.
document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage newPage; for (int i = ; i < files.Length; i++)
{
//这里的是,读取字节流
reader = new PdfReader(files[i].ToArray());
int iPageNum = reader.NumberOfPages; for (int j = ; j <= iPageNum; j++)
{
document.NewPage();
newPage = writer.GetImportedPage(reader, j);
//cb.Add(newPage);
//cb.MoveTo(0, 0);
// PageSize.A4.Height - newPage.Height 解决itext 高度的问题. itext 的y 轴默认是从下面开始
cb.AddTemplate(newPage, , pagesize.Height - newPage.Height);
} } document.Close(); byte[] fileBuffer = fs.GetBuffer(); return fs;
}
//Base64文件流
byte[] buffer = Convert.FromBase64String(decodedString);
System.IO.Stream iStream = new System.IO.MemoryStream(buffer);
try
{
int length;
long dataToRead;
string filename = sn + ".pdf";//保存的文件名称
dataToRead = iStream.Length;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "application/pdf"; //文件类型
Response.AddHeader("Content-Length", dataToRead.ToString());//添加文件长度,进而显示进度
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
while (dataToRead > )
{
if (Response.IsClientConnected)
{
length = iStream.Read(buffer, , );
Response.OutputStream.Write(buffer, , length);
Response.Flush();
buffer = new Byte[];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -;
}
}
}
catch (Exception ex)
{
Response.Write("文件下载时出现错误!");
}
finally
{
if (iStream != null)
{
iStream.Close();
}
//结束响应,否则将导致网页内容被输出到文件,进而文件无法打开
Response.Flush();
Response.End(); }