PDF export images

PDF export images

dvpriyankadvpriyanka Posts: 5Questions: 1Answers: 0

Hi to all,

I exported the table data into pdf.I have an image column in the table.
After exporting this column appears as blank column instead of holding images.

How i can encode my images to base64 format?

This is a repeated question.I am unable to get pdfmake API site.

Thanks

Subi

This question has an accepted answers - jump to answer

Answers

  • dvpriyankadvpriyanka Posts: 5Questions: 1Answers: 0

    Hi,
    I encoded my image and put in src of image tag as below.Then also image column in pdf appears blank.Is this correct?

    <td><img src=<%="\'data:rotary;base64,"+encodedImage+"\'," %> border="1" alt="img not available" height="50" width="50"></td>

    "encodedImage " is the variable that holds the encoded form of image.

    Thanks
    Subi

  • allanallan Posts: 61,635Questions: 1Answers: 10,092 Site admin
    Answer ✓

    You need to use the base64 string inside the pdfmake document, not your HTML. See the pdfmake examples for images (click the "Images" link need the top) to see how you can use images in that library.

    Use the customize callback of the pdfHtml5 button type to be able to modify the pdfmake document structure that Buttons creates.

    Allan

  • dvpriyankadvpriyanka Posts: 5Questions: 1Answers: 0

    Thank you Allan.I am going to work on this.

  • dvpriyankadvpriyanka Posts: 5Questions: 1Answers: 0
    edited June 2021

    Hi Allan,

    I have gone through the link you specified.But I couldn't find an apt solution.

    I am getting table data from the database and images from file.After executing the code I couldnt see the images in my datatable as well as in my exported page(pdf,excel...).The image column is the 2nd column in the table and appears as blank.

    I found a discussion in the below link, but the referenced url in this page was not found.
    https://datatables.net/forums/discussion/comment/99532/#Comment_99532.

    How to give "for loop" for getting the images.Also i am using a java utility for converting the image to base64 format.

    I can give you the pseudocode of what i want.

    for(count=0;count<file.length;count++)
    {
         2nd col content=Java8Base64Image.encoder(imagePath);//encoded image
    }
    

    This is my code...

    var rotNo="<%=rotaryNo%>";
    $(document).ready(function() {
          var table = $('#patientInfo').DataTable({
              dom: 'Bfrtip',
              lengthMenu: [
                            [10, 25, 50, -1],
                            ['10 rows', '25 rows', '50 rows', 'Show all']
                        ],
              lengthChange: false,
              buttons: ['pageLength', 'copy', 'excel',{
                  extend: 'pdfHtml5',
                  title: 'Details',
                  text : 'PDF',
                  titileAttr : "PDF",
                  /* download : 'open', */
                  pageSize : 'A4',
                  extension : '.pdf',
                  header : true,
                  footer : false,
                  orientation: 'landscape',
                  exportOptions : {
                        /* columns : [ 2, 3, 4, 5, 7], */
                        /* stripHtml : false */
                    },
                    customize: function (doc) {
                        doc.pageMargins = [30,50,30,50];//left,top,right,bottom
                        doc.defaultStyle.fontSize = 7;
                        doc.styles.tableHeader.fontSize = 7;
                        doc.styles.title.fontSize = 16;
                        // Remove spaces around page title
                        doc.content[0].text = doc.content[0].text.trim();
    

    //Is this the correct place to add column content of table?
    //I want to add only the images in 2nd column.Remaining data i have included in <td></td> of table in html code.But in html code also, i have this image column.If i code here, will i get images in datatable?

    ******code is not correct******
    
                        //adding image to datatable and pdf view
                        var dd = {
                            content: [
                                {
                                    image: 'too large to include',
                                    width: 150,
                                    height: 150,
                                },
                                ]
                        }
    
    ********************************************
                         // Create a header object with 3 columns
                         doc['header']=(function() {
                                return {
                                    columns: [
                                              //This is left column
                                        {
                                            
                                        alignment: 'left', 
                                            image: 'Too large to include',
                                        width:50,
                                        height:50
                                        },
                                        //This is middle column(but still appears at left side)
                                        {
                                            
                                        alignment: 'center',   
                                            image: 'Too large to include',
                                        width:50,
                                        height:50
                                        },
                                        {
                                            // This is the right column
                                            alignment: 'right', 
                                            text: rotNo,//dynamic variable
                                            fontSize: 12 
                                            
                                        }
                                    ],
                                    margin: [10, 0]
                                }
                            });
                        
                        // Create a footer
                        doc['footer']=(function(page, pages) {
                            return {
                                columns: [
                                          //This is left column
                                    {
                                    text:'Seal:',
                                        fontSize: 12
                                    },
                                            //This is middle column
                                    {
                                        text:'Signature:',
                                        fontSize: 12
                                    },
                                    
                                    
                                    {
                                        // This is the right column
                                        alignment: 'right',
                                        text: ['page ', { text: page.toString() },  ' of ', { text: pages.toString() }]
                                    }
                                ],
                                margin: [10, 0]
                            }
                        });
                     // Styling the table: create style object
                        var objLayout = {};
                        // Horizontal line thickness
                        objLayout['hLineWidth'] = function(i) { return .5; };
                        // Vertical line thickness
                        objLayout['vLineWidth'] = function(i) { return .5; };
                        // Horizontal line color
                        objLayout['hLineColor'] = function(i) { return '#aaa'; };
                        // Vertical line color
                        objLayout['vLineColor'] = function(i) { return '#aaa'; };
                        // Left padding of the cell
                        objLayout['paddingLeft'] = function(i) { return 4; };
                        // Right padding of the cell
                        objLayout['paddingRight'] = function(i) { return 4; };
                        // Inject the object in the document
                        doc.content[1].layout = objLayout;
                    }
                  }, 'print', 'colvis'],
                  /* "dom": '<"toolbar">frtip' */
                  
         }); 
         
          table.buttons().container()
          .appendTo('#patientInfo_wrapper .col-md-6:eq(0)');
        });
        
    
  • allanallan Posts: 61,635Questions: 1Answers: 10,092 Site admin

    The Excel and PDF image insertion will be completely different implementations I'm afraid. I've never attempted to insert an image into an Excel generated document, so you would need to read the open spreadsheet specification to see how that might be done - I suspect you'll need to put the images into the generated zip structure and then reference them using some specific XML tag in the spreadsheet.

    For the PDF, you'll need to loop over the rows in the pdfmake document structure that you create and insert the base64 image into the required cell.

    Neither a trivial task I'm afraid, which is why it isn't provided out of the box.

    Allan

  • dvpriyankadvpriyanka Posts: 5Questions: 1Answers: 0

    Hi Allan,

    For the PDF, you'll need to loop over the rows in the pdfmake document structure that you create and insert the base64 image into the required cell.

    The above answer is not clear to me.Can u give me some sample code?
    If you provide some dummy codes it will be more help for me.

  • allanallan Posts: 61,635Questions: 1Answers: 10,092 Site admin

    Sorry, I don't have any example code of what you are looking for. As I say, it is not a trivial task.

    Allan

  • mihir_parmarmihir_parmar Posts: 4Questions: 1Answers: 0

    Hey I'm stuck to the same thing..
    did you get the answer how to put image data in pdf?

  • luis_abreuluis_abreu Posts: 1Questions: 0Answers: 0

    Hi everyone, i found a solution and i want to share with all.

    Asp.net MVC 5 (Razor)

    Important things:
    * Pdfmake docs: http://pdfmake.org/playground.html
    * exportOptions: false (This is required to include img html data in final document. This html will be changed in the button callback)

    Steps:

    • Create your model with string property that contain the image in 64Bits.

    public static string GetImageBase64(string PhotoPath)
    {
    if (!string.IsNullOrEmpty(PhotoPath) && File.Exists(PhotoPath))
    {
    Image img = Image.FromFile(PhotoPath);

                bool IsJpeg = (PhotoPath.EndsWith(".jpg") || PhotoPath.EndsWith(".jpeg"));
    
                byte[] photo = null;
    
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, IsJpeg ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png);
                    photo = ms.ToArray();
                }
    
                if (IsJpeg)
                {
                    return String.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(photo, 0, photo.Length));
                }
                else
                {
                    return String.Format("data:image/png;base64,{0}", Convert.ToBase64String(photo, 0, photo.Length));
                }
            }
    
            return string.Empty;
        }
    
    • In View + Table:

    <td align="center"><img src="@item.Base64Image" width="80" alt="@item.FullName" style="border-radius:5px;" /></td>

    • In DataTable Config - Look on button customize callback

    buttons: [
    {
    extend: 'pdfHtml5',
    title: 'Document Tittle',
    customize: function (doc) {

        if (doc) {
            for (var i = 1; i < doc.content[1].table.body.length; i++) {
    
                var tmptext = doc.content[1].table.body[i][0].text;
                tmptext = tmptext.substring(10, tmptext.indexOf("width=") - 2);
    
                doc.content[1].table.body[i][0] = {
                    margin: [0, 0, 0, 12],
                    alignment: 'center',
                    image: tmptext,
                    width: 60,
                    height: 58
                };
            }
        }
        },
        exportOptions: {
            columns: [0, 1, 2, 3, 4, 5, 6, 7],
            stripHtml: false
        }
    }
    

    ]

    Thats it. enjoy it

This discussion has been closed.