如何使用 Java 生成具有类似 HTML 功能的 PDF

我需要使用一些具有HTML等功能的爪哇API创建PDF。基本上,我想创建一个表单,它可以从用户那里获取输入,执行一些基本的客户端验证,并使用Java以编程方式生成此PDF。我还在寻找丰富的HTML功能,如展开,折叠,超链接,在按钮单击时添加部分等。所以基本上我正在尝试创建一个类似HTML的页面,但在PDF中。

我尝试过使用itext,但只能做少数事情,并且无法在PDF中添加动态。是否有任何工具/API 支持此功能?


慕田峪4524236
浏览 169回答 1
1回答

RISEBY

PDF本身允许您嵌入(脚本的子集)。此嵌入式代码可以链接到文档事件(例如打开文档)或特定的表单元素(例如,单击按钮,更改文本输入字段中的文本)。这是他们网站上一个名为“制作PDF交互式”的页面,专注于添加表单元素。布鲁诺·洛瓦吉(iText的创始人)的书(iText在行动)也非常详细。它甚至展示了如何在PDF文档中编程计算器,第232页。我只是要在这里复制粘贴相关部分。清单 7.29 计算器public void addTextField(PdfWriter writer, Rectangle rect, String name) {    PdfFormField field = PdfFormField.createTextField(writer, false, false, 0);     field.setFieldName(name);     field.setWidget(rect, PdfAnnotation.HIGHLIGHT_NONE);     field.setQuadding(PdfFormField.Q_RIGHT);     field.setFieldFlags(PdfFormField.FF_READ_ONLY);     writer.addAnnotation(field);}    public void addPushButton(PdfWriter writer, Rectangle rect, String btn, String script) {    float w = rect.getWidth();    float h = rect.getHeight();    PdfFormField pushbutton = PdfFormField.createPushButton(writer);    pushbutton.setFieldName("btn_" + btn);    pushbutton.setWidget(rect, PdfAnnotation.HIGHLIGHT_PUSH);    PdfContentByte cb = writer.getDirectContent();    pushbutton.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, createAppearance(cb, btn, BaseColor.GRAY, w, h));    pushbutton.setAppearance(PdfAnnotation.APPEARANCE_ROLLOVER, createAppearance(cb, btn, BaseColor.RED, w, h));    pushbutton.setAppearance(PdfAnnotation.APPEARANCE_DOWN, createAppearance(cb, btn, BaseColor.BLUE, w, h));    pushbutton.setAdditionalActions(PdfName.U, PdfAction.javaScript(script, writer));    pushbutton.setAdditionalActions(PdfName.E, PdfAction.javaScript( "this.showMove('" + btn + "');", writer));    pushbutton.setAdditionalActions(PdfName.X, PdfAction.javaScript( "this.showMove(' ');", writer));    writer.addAnnotation(pushbutton);}public PdfAppearance createAppearance(PdfContentByte cb, String btn, BaseColor color, float w, float h) {    PdfAppearance app = cb.createAppearance(w, h);    app.setColorFill(color);    app.rectangle(2, 2, w - 4, h - 4);    app.fill();    app.beginText();    app.setColorFill(BaseColor.BLACK);    app.setFontAndSize(bf, h / 2);    app.showTextAligned(Element.ALIGN_CENTER, btn, w / 2, h / 4, 0);    app.endText();    return app;} 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java