I'm creating a Razor Pages Web App and I'm trying to have a button that when clicked, generates a pdf. To do this, I'm using jsPDF to convert html to pdf. I was able to get it to create and open a pdf, but when I try to add an image, I run into the problem that clicking the button doesn't any pdf. I was able to create the image-less pdf with the following code:
Code for button:
<button class="btn btn-sm btn-secondary order-button" id="testImage" onclick="this.form.submit(@Model.Project.ID)">Create Image</button>
Code in Scripts:
<script type="text/javascript">
$(function () {
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#testImage').click(function () {
var doc = new jsPDF();
doc.fromHTML($('#testImagePDF').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
//THIS IS WHERE I WAS PUTTING THE IMAGE
doc.output("dataurlnewwindow");
doc.save('TestImage_' + document.getElementById('testNum').value + '.pdf');
});
});
</script>
Html for testImage:
<form method="post" hidden>
<div id="testImagePDF">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.6/jspdf.plugin.autotable.min.js"></script>
<header style="border-bottom: 1px solid #000">
<h2 style="margin:0; padding:0">Test Image</h2>
</header>
</div>
</form>
When I add the following code to the spot commented in the scripts code, the pdf no longer opens after clicking the button:
//Code to insert the image
var line = new Image();
line.src = 'BlackRectangle.jpg';
doc.addImage(line, 'jpg', 10, 10, 80, 40);
The image 'BlackRectangle.jpg' is located in my wwwroot folder in my project. Does anyone know why after adding the image my pdf will not open and/or how to fix it so it opens and displays the image?
Notes: -This is in a Razor page's 'Details' page (created with CRUD)
If you press f12
in the browser, you will find the error. The image path is not correct.
Add a "/" before the image.
line.src = '/BlackRectangle.jpg';