How to adjust the top margin of PDF for the following problem in html2pdf.js?

Asked

Viewed 967 times

13

This is the main reference

The idea was that the image was behind, but the lib is a limited way to do it, and the text ended up being on top:

Here is an example, see that although the image is transparent, it is going up the text, the image is on line 38 of the fiddle, I could not put any image in the jsfiddle, because the CORS blocks external images, so I put the fiddle logo: FIDDLE

Here an example with the image stoned.

jsPDF

Lib I’m using based on jsPDF

Obs: I am using this lib because unfortunately the method .fromHTML() jsPDF does not align the texts to the right, just centered and left, because of this, I had to take a lib that converted the content into html2canvas first to then turn it into jsPDF and then generate the pdf, the problem is that lib first processes the content in HTML, and then, when it is ready, it allows you to play elements in footer / header, however, my PDF needs to have on the first page, a background image and a caption in the header, the caption OK, the problem is that the image was over the text.

I solved the problem with CSS, but I had a problem with the margin of the second page:

Code that generates the PDF:

var printPDF = function(name) {

    var element = '<style type="text/css">.legend{border: 1px solid #81c02e;font-size: 10px; line-height: 2em; display: block;  width: 100%;} .box-info-aluno p { line-height: 15px} p strong.ql-font-courier {font-family:courier}</style><style type="text/css">body { margin: 0 30px 30px; font-family: helvetica, "arial", sans-serif; color: #000000} p {font-family: helvetica, "arial", sans-serif} .ql-editor {font-size: 12pt; line-height: 2em; color:#000000} .ql-editor p {font-family: helvetica, arial, sans-serif; line-height: 2em; color:#000000} .ql-editor p g {font-family: helvetica, arial, sans-serif; line-height: 1.3em} .ql-font-times { font-family: "times";} .ql-font-courier { font-family: "courier";} .legend .box-info-aluno {padding: 8px; width: 100%} img { max-width: 520px; padding-top: 10px padding-bottom: 10px}</style><div class="ql-editor" data-gramm="false" data-gram_editor="false" contenteditable="false"><p class="" style="text-align:center;  line-height: 2em"><strong class="gr_" style="font-size: 24pt;"><g class="gr_">TÍTULO DA MATÉRIA</g></strong></p><p class="ql-align-right"><strong class="gr_" style="font-size: 24pt;"><g class="gr_">fdsafaf</g></strong></p><p><div class="img-box">HTML de exemplo</div></p></div>';

    var container = document.createElement('div');

  var callbackImgFundo = '/img/logo.png';
                    container.setAttribute('class', 'container-print-box');
                    container.innerHTML = element;

                    var ed = container.querySelector('.ql-editor');

                    container.removeChild(ed);

                    var container_print = document.createElement('div')
                    container_print.setAttribute('class', 'container-print');
                    var css = document.createElement('style');
                    css.setAttribute('type', 'text/css');
                    css.innerHTML = '.container-print {background: #fff url("'+callbackImgFundo+'") center top no-repeat; background-size: contain}.legend{border: 1px solid #81c02e;font-size: 10px; line-height: 2em; display: block;  width: 100%;} .ql-editor {margin: 0 50px 50px 50px!important; padding-top: 90px;}'
                    container_print.appendChild(css)
                    container_print.appendChild(ed);

                    container.appendChild(container_print);

                    element = container;




 var opt = {
                    margin:       [0, 0, 0, 0], //top, left, buttom, right
                    filename:    name + '.pdf',
                    image:        { type: 'jpeg', quality: 0.98 },
                    html2canvas:  { dpi: 192, scale: 2, letterRendering: true},
                    jsPDF:        { unit: 'pt', format: 'a4', orientation: 'portrait'},
                    pageBreak: { mode: 'avoid-all'}
                    };


var worker = html2pdf()
    .set(opt)
    .from(element)
    .toPdf()
    .get('pdf')
    .then(function(doc) {


        var totalPages = doc.internal.getNumberOfPages();


        for(var i = 1; i <= totalPages; i++ ) {   

            if (i == 1) {
                doc.setPage(i);

                //doc.addImage('/img/logo.png', 'PNG', 0, 0, 600, 850);
                 //  doc.setPage(i);
                doc.setFontType("bold");
                doc.text(330, 40, 'Matéria: ');
                doc.setFontType("normal");
                doc.text(380, 40,  'No onno nono nononono');

                doc.setFontType("bold");
                doc.text(330, 60, 'Atividade: ');
                doc.setFontType("normal");
                doc.text(390, 60, 'Nonnono onno nonono');
                doc.setFontSize(12);
                doc.setFontType("normal");
                 doc.setPage(i);

                console.log(doc.internal)

            } else {
                doc.setpage(i);
                /* QUAL MÉTODO EXISTE PARA EU SETAR 
                   A MARGEM QUANDO NÃO FOR A PRIMEIRA PÁGINA????
                 */
            }
        }



    })

    .save();
}

The method that adds the image and that: .addImage()

This is the only way that I managed to do, but now I need to be able to improve the margin of the second page, she’s cutting at the top, how could I adjust this in the callback?

The same doubt, a similar case in a Stack overflow version in English

  • Right, but your if() is no longer configured to make the first page receive the image?

  • Exactly, @Azzi, the if() configures to receive the image only on the first page, but it is getting over the text, I wanted this image behind the text..

  • If you put float in the text and align will not look good?

  • @Azzi, I don’t understand, what would that change? Maybe z-index, but it’s a PDF rule, I don’t think it changes anything.

  • @Ivanferrer By q I saw the library you are using, behind jsPdf, and its addImage has no z-Index option to indicate if you want to put in front or behind the text, more information at this link

  • Another option would be to add to HTML the image with zIndex, with fixed positions based on page size before generating the PDF

Show 1 more comment

1 answer

2


Unfortunately I could not find any solution to edit the margin after breaking the page, but I solved the problem by keeping the default margin for: [30, 0, 30, 0]. The background image, in this case has a box where is the space of the caption of the work with data of the author.

I adjusted the background image in CSS, my code looked like this:

var printPDF = function(name) {

    var element = '<style type="text/css">.legend{border: 1px solid #81c02e;font-size: 10px; line-height: 2em; display: block;  width: 100%;} .box-info-aluno p { line-height: 15px} p strong.ql-font-courier {font-family:courier}</style><style type="text/css">body { margin: 0 30px 30px; font-family: helvetica, "arial", sans-serif; color: #000000} p {font-family: helvetica, "arial", sans-serif} .ql-editor {font-size: 12pt; line-height: 2em; color:#000000} .ql-editor p {font-family: helvetica, arial, sans-serif; line-height: 2em; color:#000000} .ql-editor p g {font-family: helvetica, arial, sans-serif; line-height: 1.3em} .ql-font-times { font-family: "times";} .ql-font-courier { font-family: "courier";} .legend .box-info-aluno {padding: 8px; width: 100%} img { max-width: 520px; padding-top: 10px padding-bottom: 10px}</style><div class="ql-editor" data-gramm="false" data-gram_editor="false" contenteditable="false"><p class="" style="text-align:center;  line-height: 2em"><strong class="gr_" style="font-size: 24pt;"><g class="gr_">TÍTULO DA MATÉRIA</g></strong></p><p class="ql-align-right"><strong class="gr_" style="font-size: 24pt;"><g class="gr_">fdsafaf</g></strong></p><p><div class="img-box">HTML de exemplo</div></p></div>';

    //imagem do fundo
    var callbackImgFundo = '/img/logo.png'; 
    var container = document.createElement('div'); 
    var opt = {
               margin:       [30, 0, 30, 0], //top, left, buttom, right
               filename:    doc_name,
               image:        { type: 'jpeg', quality: 0.98 },
               html2canvas:  { dpi: 192, scale: 2, letterRendering: true},
               jsPDF:        { unit: 'pt', format: 'a4', orientation: 'portrait'},
               pageBreak: { mode: 'legacy'},
               compressPDF: true
              };
    var container = document.createElement('div');
        container.setAttribute('class', 'container-print-box');
        container.innerHTML = extra_1;
    var ed = container.querySelector('.ql-editor');
             container.removeChild(ed);
    var container_print = document.createElement('div')
        container_print.setAttribute('class', 'container-print');
    var css = document.createElement('style');
        css.setAttribute('type', 'text/css');
        //AJUSTEI O CSS DA IMAGEM DE FUNDO, DESCENDO UM POUCO A CAIXA DAS LEGENDAS
        css.innerHTML = '.container-print {background: #fff url("'+callbackImgFundo+'") center -5px no-repeat; background-size: 800px 1120px;} .ql-editor {margin: -20px 50px 50px 50px!important; padding-top: 140px;}';
        container_print.appendChild(css)
        container_print.appendChild(ed);
        container.appendChild(container_print);
        extra_1 = container;  
        var worker = html2pdf();
            worker.set(opt)
                  .from(extra_1)
                  .toPdf()
                  .get('pdf')
                  .then(function (doc) {
                     var totalPages = doc.internal.getNumberOfPages();
                     for (var i=1; i<=totalPages; i++) {
                         if (i == 1) {
                             doc.setPage(1);
                             //AJUSTEI A MARGEM DESCENDO UM POUCO O TEXTO PARA ENCAIXAR NA IMAGEM DE FUNDO DAS LEGENDAS
                             var _top_margin = 10;
                             doc.setFontType("bold");
                             doc.text(330, 40+_top_margin, 'Matéria: ');
                             doc.setFontType("normal");
                             doc.text(380, 40+_top_margin,  'No onno nono nononono');
                             doc.setFontType("bold");
                             doc.text(330, 60+_top_margin, 'Atividade: ');
                             doc.setFontType("normal");
                             doc.text(390, 60+_top_margin, 'Nonnono onno nonono');
                             doc.setFontSize(12);
                             doc.setFontType("normal");
                          } else {
                             doc.setPage(i);
                          }
                       }
                    }).save();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.