When to make a PDF document

    If you have a task - to create simple (or not quite) pdf documents in your application - it can be reports and recipes, well, or you want to print information about your objects this way, then you can use, for example, the established OpenOffice and its features (it’s hard ), or you can use the iTextSharp library (Free C # -PDF library), and I want to tell you a little example about this with which I will create such a document: There are many ways to create pdf documents using this library. Most of all I liked the way to describe using an xml document . I decided to create such xml by xslt conversion, and to palm off the data with an xml-document. Our data will look like this:







     Иван
     Иванович
     Иванов
     
      Какой то непонятный текст. Какой то непонятный текст. Какой то непонятный текст. Какой то непонятный текст. Какой то непонятный текст. Какой то непонятный текст. Какой то непонятный текст. Какой то непонятный текст.
     

     
      Другой непонятный текст. Другой непонятный текст. Другой непонятный текст. Другой непонятный текст. Другой непонятный текст. Другой непонятный текст. Другой непонятный текст. Другой непонятный текст. Другой непонятный текст.
     



    * This source code was highlighted with Source Code Highlighter.
    Next, we need to create xml for pdf (I’ll say that the link to the iText.dtd scheme in the tutorial document is broken, I give the correct link below), as I said above, for this we will write the xslt conversion :

      xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
     
     
     
     
      
       
        Информация о пользователе
       


       
        
         
        

       
        
               green="0" blue="0" left="true" right="true" top="true" bottom="true" widths="33;33;33">
        
                  right="true" top="false" bottom="true" header="true" horizontalalign="Center">
          Фамилия
          

                  right="true" top="false" bottom="true" header="true" horizontalalign="Center">
          Имя
         

                  right="false" top="false" bottom="true" header="true" horizontalalign="Center">
          Отчество
         

        

        
                  right="true" top="false" bottom="false" header="false" horizontalalign="Left">
          
           
          

         

                  right="true" top="false" bottom="false" header="false" horizontalalign="Left">
          
           
          

         

                  right="false" top="false" bottom="false" header="false" horizontalalign="Left">
          
           
          

         

        

       


       
           
      

     


     
      
       
        
       

      

      
     

     


    * This source code was highlighted with Source Code Highlighter.
    For me, they didn’t choose the most suitable description scheme, it’s too cumbersome code for a small pdf document. So, it’s not very customary to describe the colors red green and blue separately from each other, so it would be possible to make them in HEX records. As you can see in the xslt scheme - in the document there is a parameter that indicates the path of the image that will be inserted into our pdf document, a table consisting of 3 columns and a couple of paragraphs is also described there using the scheme.
    Next step: we describe all the code that will return an array of bytes to our pdf document, with comments I tried to describe the whole sequence of actions:
    public byte[] GetPdfRaw()
    {
      XmlDocument doc = new XmlDocument();
      //Загружаем данные их xml файла
      doc.Load(MapPath(@"~\Resources\UserProfile.xml"));
      XslCompiledTransform xslTransform = new XslCompiledTransform();
      //Загружаем схему XSLT преобразований
      xslTransform.Load(MapPath(@"~\Resources\ReportProcessor.xslt"));
      XsltArgumentList list = new XsltArgumentList();
      //Записываем в параметры схемы путь до картинки
      list.AddParam("picturePath", string.Empty, MapPath(@"~\Resources\Toco.jpg"));
      //Создаем поток в памяти, куда будет писаться наша xml схема для pdf документа
      using (MemoryStream stream = new MemoryStream())
      {
        //Создаем xml схему нашего pdf документа
        xslTransform.Transform(doc, list, stream);

        //Основной Font для pdf документа
        BaseFont baseFont = BaseFont.CreateFont(Environment.ExpandEnvironmentVariables(@"%systemroot%\fonts\Tahoma.TTF"),
                  "CP1251", BaseFont.EMBEDDED);

        //Создаем PDF документ
        Document document = new Document();
        using (MemoryStream pdfStream = new MemoryStream())
        {
          PdfWriter.GetInstance(document, pdfStream);
          XmlDocument d = new XmlDocument();
          string str = Encoding.UTF8.GetString(stream.ToArray()).Substring(1);
          d.LoadXml(str);
          //Определяем преобразователь из xml в pdf
          ITextHandler h = new ITextHandler(document) {DefaultFont = baseFont};
          h.Parse(d);
          //Возвращаем полученный pdf файл в формате byte[]
          return pdfStream.ToArray();
        }
      }
    }

    * This source code was highlighted with Source Code Highlighter.
    I want to pay attention to the definition of baseFont and setting it as a default font for ITextHandler. If this procedure is not performed, then the Cyrillic will not be displayed. This approach allows us to display Cyrillic, but does not allow us to use several fonts in one document. In their code (since there is source code), they always take codepage 1252 (it is directly hardwired into the code), because if you need to use several fonts in one document, then correct the code and compile the library yourself, or do not use xml as the source data (but not the fact that the problem is only in ITextHandler).
    She is still very interested in why they sometimes call classes with the letter I, in c # they are called interfaces. Of course, I understand that the library is ported from java, but still - it introduced me into a stupor first ...
    The last is the output of a pdf document in the Responce page (if you have an ASP.NET application like mine)
    protected override void OnLoad(EventArgs e)
    {
      //Записываем в Response pdf файл, указываем его MIME тип и имя файла
      HttpContext.Current.Response.Clear();
      HttpContext.Current.Response.ContentType = "application/pdf";
      HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", "report.pdf"));
      byte[] pdfRaw = GetPdfRaw();
      HttpContext.Current.Response.OutputStream.Write(pdfRaw, 0, pdfRaw.Length);
    }


    * This source code was highlighted with Source Code Highlighter
    Download example ... (for the example to work, you must also download the itextsharp library, the example uses version 4.1.2.0)

    Related links:

    Also popular now: