2011-02-02 5 views
0

Я хотел бы добавить файл PDF, содержащий информацию о идентичности и графическую информацию на каждой странице отчета службы отчетов. Этот отчет выводится из средства просмотра отчетов Dynamics CRM. Я занимался написанием расширений рендеринга, который вызывает существующее расширение экспорта PDF-файлов и с использованием компонента PDF, такого как ABCPdf.Изменение pdf-сообщений, предоставляемых службами отчетов, перед отправкой его клиенту

Я знаю, как получить визуализацию фона PDF, но мне не удалось вызвать существующее расширение рендеринга из новой реализации.

Существующий PDF-рендеринг является закрытым классом, и оказалось невозможным использовать его метод визуализации из другой реализации.

Затем я попытался вызвать сервер отчетов напрямую с помощью HTTP-запроса, и я не могу заставить его работать из-за проблемы с олицетворением. Появляется следующее сообщение об ошибке: «Нет пользователя Microsoft Dynamics CRM с указанным именем домена и идентификатором пользователя»

Я думаю, что я на правильном пути, но я понятия не имею, как получить учетные данные безопасности прямо из контекста расширение рендеринга.

Если я могу получить содержимое pdf в виде потока, я смогу добавить к нему фон.

public class PdfWithBackgroundRenderer : IRenderingExtension 
    { 


     public void GetRenderingResource(Microsoft.ReportingServices.Interfaces.CreateAndRegisterStream createAndRegisterStreamCallback, System.Collections.Specialized.NameValueCollection deviceInfo) 
     { 

     } 

     public bool Render(Report report, System.Collections.Specialized.NameValueCollection reportServerParameters, System.Collections.Specialized.NameValueCollection deviceInfo, System.Collections.Specialized.NameValueCollection clientCapabilities, ref System.Collections.Hashtable renderProperties, Microsoft.ReportingServices.Interfaces.CreateAndRegisterStream createAndRegisterStream) 
     { 
      //http://localhost/Reserved.ReportViewerWebControl.axd?ReportSession=3i414gm5fcpwm355u1ek0e3g&ControlID=417ac5edf4914b7a8e22cf8d4c7a3a8d&Culture=1043&UICulture=1033&ReportStack=1&OpType=Export&FileName=%7bF64F053A-5C28-E011-A676-000C2981D884%7d&ContentDisposition=OnlyHtmlInline&Format=PDF 
      string Url = "http://localhost/Reserved.ReportViewerWebControl.axd"; 
      Url += "?ExecutionID=" + reportServerParameters["SessionID"]; 
      Url += "&ControlID=" + Guid.Empty; 
      Url += "&Culture=1043"; 
      Url += "&UICulture=1033"; 
      Url += "&ReportStack=1"; 
      Url += "&OpType=Export"; 
      Url += "&FileName=" + report.Name; 
      Url += "&ContentDisposition=OnlyHtmlInline"; 
      Url += "&Format=PDF";    

      Stream outputStream = createAndRegisterStream(report.Name, "pdf", Encoding.UTF8, "application/pdf", true, Microsoft.ReportingServices.Interfaces.StreamOper.CreateAndRegister); 
      StreamWriter writer = new StreamWriter(outputStream);    
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 
      request.Credentials = System.Net.CredentialCache.DefaultCredentials;    

      request.Timeout = 20000; 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

      StreamReader reader = new StreamReader(response.GetResponseStream()); 
      writer.Write(reader.ReadToEnd());  
      writer.Flush(); 

      return false; 
     } 

     public bool RenderStream(string streamName, Report report, System.Collections.Specialized.NameValueCollection reportServerParameters, System.Collections.Specialized.NameValueCollection deviceInfo, System.Collections.Specialized.NameValueCollection clientCapabilities, ref System.Collections.Hashtable renderProperties, Microsoft.ReportingServices.Interfaces.CreateAndRegisterStream createAndRegisterStream) 
     { 
      return false; 
     } 

     public string LocalizedName 
     { 
      get { return "PDF Renderer with background"; } 
     } 

     public void SetConfiguration(string configuration) 
     { 

     } 
    } 

ответ

1

Существует способ, и требуется всего несколько строк. Идея состоит в вызове метода рендеринга существующего рендеринга из нового расширения рендеринга. Это даст вам результат рендеринга как поток, который вы можете изменить.

Я не нашел решение в Интернете, но нашел некоторые ответы на форуме, утверждая, что этого не может быть достигнуто.

Жесткая часть заключается в том, чтобы разглядеть функцию делегата, которая используется. Как только вы поймете, что происходит, решение становится простым.

Этот код протестирован с Reporting Services 2008. Этот метод очень полезен, если вы хотите изменить результаты рендеринга, созданные существующими исключениями SSRS-рендеринга. Вы можете выполнять замену строк, изменять CSV-файл в соответствии с вашими потребностями или как в нашем случае подписывать или обновлять PDF-документ.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Microsoft.ReportingServices.OnDemandReportRendering; 
using Microsoft.ReportingServices.Rendering.ImageRenderer; 
using System.Globalization; 
using System.IO; 
using System.Net; 

namespace ReportRendering.PDF 
{ 

    public class PdfWithBackgroundRenderer : IRenderingExtension 
    { 
     //Add the existing rendering extension to the new class 
     //In this case PDfRenderer from the ImageRenderer namespace 
     private PDFRenderer pdfRenderer; 

     //Stream to which the intermediate report will be rendered 
     private Stream intermediateStream; 
     private string _name; 
     private string _extension; 
     private Encoding _encoding; 
     private string _mimeType; 
     private bool _willSeek; 
     private Microsoft.ReportingServices.Interfaces.StreamOper _operation; 

     //Inititate the existing renderer in the constructor 
     public PdfWithBackgroundRenderer() 
      : base() 
     { 
      pdfRenderer = new PDFRenderer(); 
     } 


     public void GetRenderingResource(Microsoft.ReportingServices.Interfaces.CreateAndRegisterStream createAndRegisterStreamCallback, 
      System.Collections.Specialized.NameValueCollection deviceInfo) 
     { 

     } 

     //New implementation of the CreateAndRegisterStream method 
     public Stream IntermediateCreateAndRegisterStream(string name, string extension, Encoding encoding, string mimeType, bool willSeek, Microsoft.ReportingServices.Interfaces.StreamOper operation) 
     { 
      _name = name; 
      _encoding = encoding; 
      _extension = extension; 
      _mimeType = mimeType; 
      _operation = operation; 
      _willSeek = willSeek; 
      intermediateStream = new MemoryStream(); 
      return intermediateStream; 
     } 

     public bool Render(Report report, 
      System.Collections.Specialized.NameValueCollection reportServerParameters, 
      System.Collections.Specialized.NameValueCollection deviceInfo, 
      System.Collections.Specialized.NameValueCollection clientCapabilities, 
      ref System.Collections.Hashtable renderProperties, 
      Microsoft.ReportingServices.Interfaces.CreateAndRegisterStream createAndRegisterStream) 
     { 

      //Call the render method of the intermediate rendering extension 
      pdfRenderer.Render(report, reportServerParameters, deviceInfo, clientCapabilities, ref renderProperties, new Microsoft.ReportingServices.Interfaces.CreateAndRegisterStream(IntermediateCreateAndRegisterStream)); 

      //Register stream for new rendering extension 
      Stream outputStream = createAndRegisterStream(_name, _extension, _encoding, _mimeType, _willSeek, _operation); 


      intermediateStream.Position = 0; 

      //put stream update code here 

      //Copy the stream to the outout stream 
      byte[] buffer = new byte[32768]; 

      while (true) { 
       int read = intermediateStream.Read(buffer, 0, buffer.Length); 
       if (read <= 0) break; 
       outputStream.Write(buffer, 0, read); 
      } 

      intermediateStream.Close(); 

      return false; 
     } 

     public bool RenderStream(string streamName, Report report, System.Collections.Specialized.NameValueCollection reportServerParameters, System.Collections.Specialized.NameValueCollection deviceInfo, System.Collections.Specialized.NameValueCollection clientCapabilities, ref System.Collections.Hashtable renderProperties, Microsoft.ReportingServices.Interfaces.CreateAndRegisterStream createAndRegisterStream) 
     { 
      return false; 
     } 

     public string LocalizedName 
     { 
      get { return "PDF Renderer with background"; } 
     } 

     public void SetConfiguration(string configuration) 
     { 
      pdfRenderer.SetConfiguration(configuration); 
     } 


    } 
} 
+0

Пожалуйста Витит блог моего Colleage по поводу этого решения: [ссылка] (http://www.broes.nl/2011/02/pdf-watermarkbackground-rendering-extension-for-ssrs-part-1/) – jhoefnagels

Смежные вопросы