2

The output says that PDF is corrupted or Failed to load PDF. How to fix this?

Is there something wrong with the blob? I checked the blob and it returns blob:null/alphanumeric

function ExportPDF(elem, filename='') {
    var blob = new Blob([html], { type: 'application/pdf' } );
  
    // Specify link url
    var url = URL.createObjectURL(blob);

    // // Specify file name
    filename = filename ? filename + '.pdf' : 'document.pdf';

    // // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if (navigator.msSaveOrOpenBlob) {
        navigator.msSaveOrOpenBlob(blob, filename);
    } else {
        // Create a link to the file
        downloadLink.href = url;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }

    document.body.removeChild(downloadLink);
}
<div id="export"> 
  <text> 治験課題名 </text>
</div>

<button onclick="ExportPDF('export');">Export as PDF</button>
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
maria
  • 21
  • 2
  • What does the file actually contain? Have you tried opening it with a text editor? This code isn't creating a real PDF file, it saves whatever is in `html` to a file with a `.pdf` extension. Unless `html` is actually a binary buffer containing the bytes of a real PDF file, the file will be invalid no matter the contents – Panagiotis Kanavos Jan 27 '20 at 13:55
  • @PanagiotisKanavos I just want to export what was in the text tag to pdf. I think that the javascript is not correct since it doesn't give me the expected output I want. Is there something you can help? – maria Jan 29 '20 at 03:33
  • What you want is impossible. PDF isn't text - you can't fake it with a `.pdf` extension. You need a library that creates PDF files – Panagiotis Kanavos Jan 29 '20 at 08:14
  • Does this answer your question? [Generating PDF files with JavaScript](https://stackoverflow.com/questions/742271/generating-pdf-files-with-javascript) – Panagiotis Kanavos Jan 29 '20 at 08:16
  • I tried using JSPDF. But it generates garbage texts. – maria Jan 29 '20 at 08:19
  • PDF isn't text. What did you try, what didn't work? You can't assume you're the only person that ever tried to use jsPDF. Others would have noticed if it didn't work at all. There probably other questions asking how to create PDF files with non-English text. There are a *lot* of other libraries too – Panagiotis Kanavos Jan 29 '20 at 08:29
  • And an exact duplicate [JavaScript pdf generation library with Unicode support](https://stackoverflow.com/questions/38352664/javascript-pdf-generation-library-with-unicode-support) asking for Japanese text. The answer uses PDFKit – Panagiotis Kanavos Jan 29 '20 at 08:35

0 Answers0