In this blog we will discuss how to merge more than one PDF in single PDF file generated by RDLC report.
Here is code to generate PDF report data (in memory stream) from rdlc file:
C# code:
public MemoryStream WritePDFReport(List<ReportModel> reportData)
{
Microsoft.Reporting.WinForms.Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
"</DeviceInfo>";
ReportViewer viewer = new ReportViewer();
try
{
string exeFolder = System.AppDomain.CurrentDomain.BaseDirectory;
string reportPath = Path.Combine(exeFolder, string.Format(@"Sample.rdlc”));
viewer.ProcessingMode = ProcessingMode.Local;
viewer.LocalReport.ReportPath = reportPath;
ReportDataSource ds = new ReportDataSource("ReportDataSet", reportData);
viewer.LocalReport.DataSources.Add(ds);
viewer.LocalReport.Refresh();
byte[] bytes = viewer.LocalReport.Render("PDF", deviceInfo,
out mimeType, out encoding, out extension, out streamIds, out warnings);
return new MemoryStream(bytes);
}
catch (Exception)
{
throw;
}
finally
{
viewer.LocalReport.Dispose();
viewer = null;
}
}
WritePDfReport() method takes report data as input and it generates report by using ReportViewer Class and it calls Render method to generate the memory stream of report.
the above code generates only single PDF file and if you want to generate more than one fPDF iles and merge all into a single PDF file, for this you need to use PDFsharp.
Here is code to merge PDF files
C# Code:
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
List<ReportModel> reportData;
PdfDocument document = new PdfDocument();
for (int ix = 0; ix < 4; ix++)
{
PdfDocument tempPDFDoc = PdfReader.Open(WritePDFReport(reportData), PdfDocumentOpenMode.Import);
for (int i = 0; i < tempPDFDoc.PageCount; i++)
{
PdfPage page = tempPDFDoc.Pages[i];
document.AddPage(page);
}
}
document.Save("C://logs/sample.pdf");
document.Close()
· Call WritePDFReport() method to generate report and get memory stream ( in byte arrays)
· Import report data into temporary PdfDocument object - tempPDFDoc by Call PdfReader.Open() method
· Add the imported PDF page from into Main PdfDocument object – document.
· Call PdfDocument ‘s save method to save all imported pdf page into single pdf page (sample.pdf)
· Call Close() method of PdfDocument – document
For more information about PDFSharp dll, Code Samples and installation steps please visit at below URLs
Thanks for visiting!!