question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Save PDF into local server

See original GitHub issue

Hi, html2pdf is awesome!

Congrats for this solution!

My html content is huge, so I slice into parts avoiding canvas size limitations. 😄

let fileName = "evaluation_xxx.pdf";

// Assuming "pages" is an array of HTML elements or strings that are separate pages:

let pages = [];
$('.evaluation-page-template.page').each(function () {
      pages.push($(this)[0]);
});

// Generate the PDF.
let worker = html2pdf().from(pages[0]).set({
      margin: 0,
      filename: fileName,
      html2canvas: { scale: 2 },
      jsPDF: {orientation: 'portrait', unit: 'pt', format: 'a4', compressPDF: true}
}).toPdf();

pages.slice(1).forEach(function (page) {
      worker = worker.get('pdf').then(function (pdf) {
          pdf.addPage();
      }).from(page).toContainer().toCanvas().toPdf();
});
worker = worker.save();

Can I save PDF file into server instead of download it? Maybe with some upload API to send to server? Can you help me?

Thanks!!!

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:7

github_iconTop GitHub Comments

13reactions
bidianqingcommented, Mar 21, 2020

@gcuculi Why need dataURI convert to blob?

html2pdf().set(opt).from(element).toPdf().get('pdf').then(function (pdfObj) {
    const perBlob = pdfObj.output('blob');

    var formData = new FormData();
    formData.append('file', perBlob, opt.filename);
    
});

11reactions
gcuculicommented, Dec 20, 2019

Hi, everyone!!!

Many hours later I figured out using parts of other codes that I found around. My solution:

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}
// Final file name
let fileName = "evaluation_xxx.pdf";

// Assuming "pages" is an array of HTML elements or strings that are separate pages:
let pages = [];
$('.evaluation-page-template.page').each(function () {
    pages.push($(this)[0]);
});

// Generate the PDF.
let worker = html2pdf().from(pages[0]).set({
    margin: 0,
    filename: fileName,
    html2canvas: { scale: 2 },
    jsPDF: { orientation: 'portrait', unit: 'pt', format: 'a4', compressPDF: true}
}).toPdf();
    
pages.slice(1).forEach(function (page) {
    worker = worker.get('pdf').then(function (pdf) {
        pdf.addPage();
    }).from(page).toContainer().toCanvas().toPdf();
});

worker = worker.output("datauristring").then(function(pdf) {

    const variable_1 = "x";
    const variable_2 = "y";

    const preBlob = dataURItoBlob(pdf);
    const file = new File([preBlob], fileName, {type: 'application/pdf'}); 

    let data = new FormData();
    data.append("variable_1", variable_1);
    data.append("variable_2", variable_2);
    data.append("file", file);

    $.ajax({
        method: 'POST',
        url: "api/uploadPDF.php",
        data: data,
        processData: false,
        contentType: false
    }).success(function (data, textStatus, jqXHR) {
        data = JSON.parse(data);
    }).error(function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    });

});

PHP code

$file = (isset($_FILES['file']) ? $_FILES['file'] : NULL);

@move_uploaded_file($file['tmp_name'], $filePath . $fileName)

I know html2pdf is recommended to let things in client side, but this solution (save into server feature) is not part of initial scope of this project, so save me a lot of time.

Thanks @eKoopmans for this awesome work.

Merry Christmas and a great new year for all of us!!!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Save pdf to local server - php - Stack Overflow
This worked for me, using the fpdf library, $pdf_data = $pdf->Output(); These 3 lines allow me to save the .pdf so I can...
Read more >
How to save pdf to file server location? - CodeProject
I am able to get the generated pdf to download locally but when I send it to the file folder it gets corrupted...
Read more >
Save modified PDF on server - PSPDFKit
A: There are 2 ways you can do this: Save the whole PDF: You can export the modified PDF as an arrayBuffer using...
Read more >
How do I save a PDF locally on the server? - SugarClub
I just want to take a PDF Manager record and turn it into a PDF and save that PDF locally on the server....
Read more >
Save Pdf documents in server side | ASP.NET Web Forms
How to save a PDF document by replacing the original PDF document in the server side of the PDF viewer control? · PdfViewerHelper...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found