ItextSharp将多张pdf内容合并至一个pdf中

此详例主要是借助使用ReportViewer控件自带的Render方法将文件流读取至创建的pdf文件

简单介绍ReportViewer控件的使用

首先拖拽一个reportViewer控件,并设置显示样式

其中标签LocalReport控件中的ReportPath属性值需要填写添加的报表文件所在的相对路径

在添加报表文件时,添加的参数对象名和数据集的名字要和赋值处的名字保持一致(打开vs菜单栏的视图》报表数据可具体设置)

为确保pdf文件的美观,可在vs菜单栏的报表》报表属性可具体设置pdf文件样式

<div style="word-break: break-all">
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="14px"
InteractiveDeviceInfos="(集合)" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt"
Width="1000px" Height="600px" ShowBackButton="False" ShowPageNavigationControls="False" >
<LocalReport ReportPath="..ShowInvoiceDetail.rdlc" >
</LocalReport>
</rsweb:ReportViewer>
</div>

//配置数据源类型必须为list类型
this.ReportViewer1.LocalReport.DataSources.Clear();
this.ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", currentInvoice));
this.ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet2", currentInvoiceDetail));
this.ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet3", cpyInfo));
ReportParameter[] p = new ReportParameter[6]; //定义传递参数
p[0] = new ReportParameter("CapTotal", capTotal);
p[1] = new ReportParameter("Total", total);
p[2] = new ReportParameter("AmountSumString", OutputVATBLL.DecimalRound.Round(amountSum));
p[3] = new ReportParameter("TaxationSumString", OutputVATBLL.DecimalRound.Round(taxationSum));
p[4] = new ReportParameter("UserName", userName);
p[5] = new ReportParameter("DescriptionString", currentInvoice[0].Description == null ? "" : currentInvoice[0].Description);
ReportViewer1.LocalReport.SetParameters(p);//设置传递参数
ReportViewer1.ShowParameterPrompts = false;
ReportViewer1.LocalReport.Refresh();//刷新报表
ReportViewer1.Visible = true;

将多个pdf文件合并至一个pdf文件的具体实现详例

第一步:添加引用文件

备注:使用iTextSharp将多张pdf内容合并到一个pdf中需要应用一下文件

using iTextSharp.text;
using iTextSharp.text.pdf;

第二步:

protected void ExportPdfBtn_Click(object sender, EventArgs e)
{
string filename =Guid.NewGuid().ToString();
string oType = "PDF";
try
{
string tmpDirPath = Server.MapPath("../../PdfFiles/TempFiles");
DeleteAllPdf(tmpDirPath);
ResponseFile(oType, filename);

}
catch (Exception ex)
{
AlertExceptionString(Page,ex);
return;
}
}

public void ResponseFile(string fType, string fileNameString)
{
try
{
string dirPath = Server.MapPath("../../PdfFiles");
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string tmpDirPath = Server.MapPath("../../PdfFiles/TempFiles");
if (!Directory.Exists(tmpDirPath))
{
Directory.CreateDirectory(tmpDirPath);
}
string returnFilePath = dirPath + "\" + fileNameString + ".Pdf";
if (File.Exists(returnFilePath))
{
File.Delete(returnFilePath);
}
//获取地址栏参数
var codeList = Request["CodeStrs"];
//转换数据
var codeArr = codeList.Split(',');
for (var i = 1; i <= codeArr.Length; i++)
{
var guid = Guid.NewGuid().ToString();
string createFilePath = tmpDirPath + "\" + guid + ".Pdf";
if (File.Exists(createFilePath))
{
File.Delete(createFilePath);
}
Warning[] warnings;
string[] streamids;
string mimeType = "";
string encoding = "";
string extension = "";
byte[] bytes;
List<byte[]> list = new List<byte[]>();
FileStream fs = new FileStream(createFilePath, FileMode.Create);
BindReportData(i);

//此处用的是ReportViewer控件自带的读取字符流的方法
bytes=ReportViewer1.LocalReport.Render(fType, null, out mimeType, out encoding, out extension,
out streamids, out warnings);
fs.Write(bytes, 0, bytes.Length);//使用从缓冲区读取的数据将字节块写入该流。
fs.Flush();
fs.Close();
}
MergePdf(tmpDirPath, returnFilePath);
ExcelDownload(returnFilePath);
DeleteAllPdf(tmpDirPath);

}
catch (Exception exception)
{
AlertString(Page, exception.Message.Replace("'",""));
}
}

//合并pdf
public static void MergePdf(string DirectoryPath, string outpath)
{
List<string> fileList=new List<string>();
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(DirectoryPath);
FileInfo[] fInfos = directory.GetFiles("*.pdf");
BubbleSort(fInfos);
foreach (FileInfo temp in fInfos)
{
fileList.Add(DirectoryPath+"\"+temp.Name);
}
mergePdfFiles(fileList,outpath);
}

public static void BubbleSort(FileInfo[] Arr)
{
for (int i = 0; i < Arr.Length; i++)
{
for (int j = i; j < Arr.Length; j++)
{
if (Arr[i].LastWriteTime > Arr[j].LastWriteTime)//按创建时间(升序)
{
FileInfo temp = Arr[i];
Arr[i] = Arr[j];
Arr[j] = temp;
}
}
}
}

/// <summary>
/// 合成pdf文件
/// </summary>
/// <param name="fileList"></param>
/// <param name="outMergeFile"></param>
public static void mergePdfFiles(List<string> fileList, string outMergeFile)
{
PdfReader reader;

//此处将内容从文本提取至文件流中的目的是避免文件被占用,无法删除
FileStream fs1 = new FileStream(fileList[0], FileMode.Open);
byte[] bytes1 = new byte[(int)fs1.Length];
fs1.Read(bytes1, 0, bytes1.Length);
fs1.Close();
reader = new PdfReader(bytes1);
reader.GetPageSize(1);
// iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(1000,800);//设置样式
iTextSharp.text.Rectangle rec = reader.GetPageSize(1);
float width = rec.Width;
float height = rec.Height;
//创建一个文档变量
iTextSharp.text.Document document=new iTextSharp.text.Document(rec,50,50,50,50);
//创建该文档
PdfWriter pdfWrite = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
//打开文档
document.Open();
//添加内容
PdfContentByte contentByte = pdfWrite.DirectContent;
PdfImportedPage newPage;
for (int i = 0; i < fileList.Count; i++)
{
//File.Delete(fileList[i]);
FileStream fs = new FileStream(fileList[i], FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
reader = new PdfReader(bytes);
int pageNum = reader.NumberOfPages;//获取文档页数
for (int j = 1; j <= pageNum; j++)
{
document.NewPage();
newPage = pdfWrite.GetImportedPage(reader, j);
contentByte.AddTemplate(newPage,0,0);
}
File.Delete(fileList[i]);
}
document.Close();
}

/// <summary>
/// 删除一个文件夹里的所有文件
/// </summary>
/// <param name="filePath"></param>
public static void DeleteAllPdf(string DirectoryPath)
{
System.IO.DirectoryInfo dic = new System.IO.DirectoryInfo(DirectoryPath);
if (dic.Exists)
{
FileInfo[] fInfo = dic.GetFiles("*.pdf");
foreach (FileInfo temp in fInfo)
{
File.Delete(DirectoryPath+"\"+temp.Name);
}
}
}

public void ExcelDownload(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/ms-pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(System.IO.Path.GetFileName(filePath), Encoding.UTF8));
Response.AddHeader("Content-Length", bytes.Length.ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.Close();
File.Delete(filePath);
}

仅用于积累和借鉴。。。。。。。

原文地址:https://www.cnblogs.com/DreakSeeker/p/8143395.html