如何将HTML转换为字符串以在JavaScript中生成PDF



我想将我的HTML DOM元素转换为字符串,以便可以使用它生成Pdf。

我在JavaScript中尝试了以下代码,但它返回了一个HTML元素。

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>

这将返回以下内容:

<!--!-->
<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><!--!-->

因此,我无法通过将此字符串传递给PdfDocument document = htmlConverter.Convert(htmlstring);来转换为PDF。它抛出Error: Syncfusion.Pdf.PdfException: Html conversion failed的异常。如何将HTML DOM元素转换为字符串?

HTML转换器中报告的异常可能是由于在URL转换方法中转换HTML字符串而发生的。带有单个参数的convert方法用于URL到PDF的转换。请参阅下面的代码片段,将HTML字符串转换为PDF。请尝试使用下面的代码片段进行转换,并让我们知道结果。

//Convert HTML string to PDF  
PdfDocument document = htmlConverter.Convert(htmlText, baseUrl);  

有关更多信息,请参阅以下链接,

UG:https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/webkit#html-字符串到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

注意:我为Syncfusion工作。

按照JavaScript的设置方式,您的代码实际上是返回一个字符串。

此处显示:

var element=document.getElementById("pdfdiv"); 
var str = element.innerHTML;
console.log(str)
console.log("The variable type is...")
console.log(typeof(str))
<div id="pdfdiv">Make me into a string, please!</div>

解决方案很可能存在于您似乎正在使用的库中:Syncfusion。根据文档,Convert()函数将URL作为参数,而不是HTML字符串。这就是导致程序抛出错误的原因。

我建议列出您在代码中使用的所有库,以便将来在StackOverflow上提问。

最新更新