I want to convert my HTML DOM element to a string so that I can use it for Pdf generation.
I tried the following code in JavaScript but it returns an HTML element.
function getHtmlString() {
var element=document.getElementById("pdfdiv");
var str = element.innerHTML;
console.log(str);
return str;
};
<div id="pdfdiv">
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<!--<h3 style="margin-left:150px;"><strong> Patient Details</strong></h3>-->
<table width="100%" style="padding:0px 105px">
<thead>
<tr>
<th>
</th>
</tr>
<tr>
<th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<table style="float:left" width="75%">
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
"Hi" @order.Id
</td>
<td>
<h2><strong> Patient Order</strong></h2>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</body>
</html>
</div>
This returns the following:
<!--!-->
<html><!--!-->
<!--!-->
<meta charset="utf-8">
<title></title>
<body><!--!-->
<table width="100%" style="padding:0px 105px"><!--!-->
<!--!--><thead>
<tr>
<th>
</th>
</tr>
<tr>
<th>
</th>
</tr>
</thead>
<tbody><!--!-->
<tr><!--!-->
<td><!--!-->
<table style="float:left" width="75%"><!--!-->
<!--!--><thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><!--!-->
<tr><!--!-->
<td><!--!-->
"Hi" 4<!--!-->
</td><!--!-->
<!--!--><td>
<h2><strong> Patient Order</strong></h2>
</td>
</tr><!--!-->
</tbody><!--!-->
</table><!--!-->
</td><!--!-->
</tr><!--!-->
</tbody><!--!-->
</table><!--!-->
</body><!--!-->
Due to this, I can't covert to PDF by passing this string to PdfDocument document = htmlConverter.Convert(htmlstring);
. It throws an exception of Error: Syncfusion.Pdf.PdfException: Html conversion failed
. How can I convert the HTML DOM element to a string?
The reported exception in the HTML converter may occur due to converting HTML string in a URL conversion method. The convert method with a single argument is for URL to PDF conversion. Kindly refer to the below code snippet for converting HTML string to PDF. Kindly try the conversion with the below code snippet and let us know the result.
//Convert HTML string to PDF
PdfDocument document = htmlConverter.Convert(htmlText, baseUrl);
Please refer below links for more information,
UG: https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/webkit#html-string-to-pdf
KB: https://www.syncfusion.com/kb/9890/how-to-convert-html-string-to-pdf-using-c-and-net
https://www.syncfusion.com/kb/8174/how-to-preserve-resources-during-html-string-to-pdf-conversion
Note : I work for Syncfusion.