1 回答

TA貢獻1856條經(jīng)驗 獲得超5個贊
PDF本身允許您嵌入(腳本的子集)。
此嵌入式代碼可以鏈接到文檔事件(例如打開文檔)或特定的表單元素(例如,單擊按鈕,更改文本輸入字段中的文本)。
這是他們網(wǎng)站上一個名為“制作PDF交互式”的頁面,專注于添加表單元素。
布魯諾·洛瓦吉(iText的創(chuàng)始人)的書(iText在行動)也非常詳細(xì)。它甚至展示了如何在PDF文檔中編程計算器,第232頁。
我只是要在這里復(fù)制粘貼相關(guān)部分。
清單 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;
}
添加回答
舉報