In order to render, you need to first convert to byte array.
using Microsoft.Reporting.WebForms; // Make sure to add reference to Microsoft.ReportViewer.WebForms or Microsoft.Reporting.WinForms
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections.Generic; // Required for Warning[]
public static byte[] RenderReportToPDF(LocalReport report, string deviceInfo)
{
string mimeType, encoding, extension;
Warning[] warnings;
string[] streams;
byte[] renderedBytes = report.Render(
"PDF",
deviceInfo,
out mimeType,
out encoding,
out extension,
out streams,
out warnings);
return renderedBytes;
}
public static void ExportRdlcToPdf(LocalReport report, string filePath, string deviceInfo = "<DeviceInfo><OutputFormat>PDF</OutputFormat></DeviceInfo>")
{
try
{
byte[] pdfBytes = RenderReportToPDF(report, deviceInfo);
// Create a new PDF document from the rendered bytes
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
using (Document document = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
using (MemoryStream ms = new MemoryStream(pdfBytes))
{
PdfReader reader = new PdfReader(ms);
for (int page = 1; page <= reader.NumberOfPages; page++)
{
document.NewPage();
PdfImportedPage importedPage = writer.GetImportedPage(reader, page);
document.Add(new PdfContentByte(writer).AddTemplate(importedPage, 0, 0));
}
}
}
}
}
catch (System.Exception ex)
{
// Handle exceptions appropriately, e.g., logging
Console.WriteLine($"Error exporting to PDF: {ex.Message}");
throw; // Re-throw or handle as needed
}
}
// Example Usage:
// Create a LocalReport instance
// var report = new LocalReport();
// report.ReportPath = "Path/To/Your/Report.rdlc";
// report.DataSources.Add(new ReportDataSource("YourDataSourceName", yourData));
// Example DeviceInfo (optional, but recommended for high resolution):
// string deviceInfo = "<DeviceInfo><OutputFormat>PDF</OutputFormat><PageWidth>8.5in</PageWidth><PageHeight>11in</PageHeight><MarginTop>0.5in</MarginTop><MarginLeft>0.5in</MarginLeft><MarginRight>0.5in</MarginRight><MarginBottom>0.5in</MarginBottom></DeviceInfo>";
// Call the export function
// ExportRdlcToPdf(report, "Path/To/Save/YourReport.pdf", deviceInfo);