I want to save this html code to PDF:
<div id="mycontent">
<h1>Sample PDF from HTML</h1>
<p>This text you'll find in PDF page.</p>
</div>
Javascript I am using is:
const mycontent = document.getElementById('mycontent').outerHTML;
const blob = new Blob([mycontent], { type: 'application/pdf' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'file.pdf';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
I can see the dialog to save and after save, I open the file to read it. I am getting this message:
The content type is not valid to read the file or the file is damaged.
What is wrong?
2
Answers
You won’t magically get a PDF just by saving some HTML text in a file with the extension
.pdf
.You’ll need a library like jsPDF or html2pdf to layout the text on a page, then write it out as a PDF file – or, of course, you can read the PDF specification and write a PDF-writing implementation yourself – it’s just about 700 pages.
What you need is a block of code to download
If you write it as a file (TEXT.PDF) and get all those decimal numbers correct it should work, as intended after download so here:
Clearly this is a problematic method as that code bit&byte stream needs to be file name length handled with the correct "Decimal" memory file stream addresses. The simplest way arround that is convert the "file BLOB" into a larger "data BLOB" then add that as a data:uri.
I have included that here but Web site security will usually not alow serving so right click and download should work. Or cut and paste the web page below into a html file.