这是我使用itext pdf库从java创建pdf的代码,我接替了它。我现在的问题是我无法在调用onload时从html添加javascript代码,也不能从java代码添加javascript代码。 我没有任何例外。 我做错了什么?有可能实现吗?
public class App {
public static final String src = "new.pdf";
public static final String HTML = "test.html";
public static void main(String[] args) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(src));
// writer.addJavaScript("<script>alert('asdas')</script>");
document.open();
document.setJavaScript_onLoad("yourFunction()");
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(HTML));
document.close();
}
}
<html>
<head>
<style>.col{padding:3px 20px 3px 20px}</style>
<script type="text/javascript">
function yourFunction(){
alert('You clicked the bottom text');
}
</script>
</head>
<body style="font-family:tahoma" onload="yourFunction()">
<div style="background:rgb(230,230,230); padding:5px ;border:1px solid black;">
<b style="color:rgb(51,153,255)">Sample header</b>
<img style="float:right" height="25px" width="80px" src="resources/images/itext.png"/>
</div>
<br/>
<table border='0' style='border-collapse: collapse;'>
<tr>
<td class="col">String 1</td>
<td class="col">: 1234354545</td>
</tr>
<tr>
<td class="col">String 32</td>
<td class="col">: rere</td>
</tr>
<tr>
<td class="col">String 3</td>
<td class="col">: ureuiu</td>
</tr>
<tr>
<td class="col">Date</td>
<td class="col">: dfdfjkdjk</td>
</tr>
</table>
<br/>
<br/>
<br/>
<hr/>
<br/>
Contact us
</body>
</html>
答案 0 :(得分:1)
XMLWorker在生成PDF文件时无法解析Javascript。事实上,XMLWorker会忽略它,因此无论HTML文件中的函数是什么,尝试使用setJavaScript_onLoad()调用它都不会起作用。我不确定您在此处尝试实现的目标,但您可以使用Java功能来评估嵌入式Javascript。您只是无法在iText上下文中运行脚本。
如果您需要在PDF中嵌入Javascript,我会在解析HTML后使用iText添加它。这要求您单独使用Javascript并调整为提供的API。您需要检查Javascript API以查看您可以在PDF文件中执行的操作。通常,您会添加&#34;其他操作&#34;字典到页面,表单等,以便能够运行Javascript。您可以查看有关如何构建AA字典的PDF规范以及提供的触发器。但是,不要期望能够将Javascript for HTML放在PDF中并期望它能够开箱即用。
您还需要更加具体地了解您在Javascript中尝试做什么,以及当您尝试为我们做一些更具体的答案时。