Sunday 18 June 2023

How to Generate an SSRS Report as a Password-Protected PDF Using ASP.Net C#

Case scenario, apply password on pdf generated with SSRS report.

DLL Required.


Microsoft.ReportViewer.WebForms.dll
Microsoft.ReportViewer.Common.dll
itextsharp.dll


using iTextSharp.text.pdf;
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
 
namespace ConsoleApplication1
{
    public class SSRSReport
    {
        public void Report()
        {
            string path = "Report Path";
            string ssrsURL = "Report Server URL";
            string ssrsUser = "Report Server User";
            string ssrsPass = "Report Server Password";
 
            ReportViewer reportViewer = new ReportViewer();
            reportViewer.ProcessingMode = ProcessingMode.Remote;
            reportViewer.ServerReport.ReportServerCredentials
                = new ReportCredentials(new NetworkCredential(ssrsUser.Trim(), ssrsPass.Trim(), ""));
            reportViewer.ServerReport.ReportServerUrl = new Uri(ssrsURL);
            reportViewer.ServerReport.ReportPath = path;
            reportViewer.ServerReport.SetParameters(new List<ReportParameter>() {
                new ReportParameter("Param1", "Value1"),
                new ReportParameter("Param2", "Value2")
            });
            reportViewer.ServerReport.Refresh();
 
            byte[] bytes = reportViewer.ServerReport.Render("pdf");

            using (MemoryStream inputData = new MemoryStream(bytes))
            {
                using (MemoryStream outputData = new MemoryStream())
                {
                    string pdfPassword = "test@123";
                    PdfReader reader = new PdfReader(inputData);
                    PdfEncryptor.Encrypt(reader, outputData, true, pdfPassword, pdfPassword, PdfWriter.ALLOW_SCREENREADERS);
                    byte[] passwordFileBytes = outputData.ToArray();
 
                    if (!Directory.Exists(@"D:\Report\"))
                        Directory.CreateDirectory(@"D:\Report\");
 
                    File.WriteAllBytes(@"D:\Report\WithoutPassword.pdf", bytes);
                    File.WriteAllBytes(@"D:\Report\WithPassword.pdf", passwordFileBytes);
 
                    //Line of code used in the web application
                    //Response.ContentType = "application/pdf";
                    //Response.AddHeader("content-disposition", "attachment;filename=Sample.pdf");
                    //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    //Response.BinaryWrite(passwordFileBytes);
                    //Response.End();
                }
            }
        }
    }
}

No comments:

Post a Comment