2026年1月18日 星期日

用iTextSharp變成互動PDF

用iTextSharp變成互動PDF (Interactive PDF)
我發現互動pdf可以讓使用者參與,可以輸入表單欄位,並檢查資料這樣PDF就可以變成Game了。
所以我就將crystal report產出的PDF資料,再用iTextSharp將PDF加入TextField,PushbuttonField變成互動PDF,就可以讓使用者輸入答案或直接看答案。
成語滿格 CROSSWORD 下載互動 sample pdf
    
//用iTextSharp加入TextField
//96個填入格子 預設空白
for (int i = 0; i < 96; i++)
{
    X = i % 8;
    Y = i / 8;
    var W = new TextField(stamp.Writer, new Rectangle(x1, y1, x2, y2), "W" + i.ToString())
    {
        Alignment = Element.ALIGN_CENTER & Element.ALIGN_MIDDLE,
        MaxCharacterLength = 1,
        FontSize = 11,
        Font = baseFont,
        TextColor = Color.BLUE,
    };

    PdfFormField textField = W.GetTextField();
    //輸入完檢查 正確否   
    string jschk = string.Format("chk(event,{0});", i.ToString());
    PdfAction onBlur = PdfAction.JavaScript(jschk, stamp.Writer);
    textField.SetAdditionalActions(PdfName.BL, onBlur);  // On blur
    stamp.AddAnnotation(textField, 1);
}

//用iTextSharp加入PushbuttonField
//數個 看答案按鈕   hover可以看提示,click可以直接show答案 
string js = string.Format("showdata({0});",idx.ToString());            
PdfAction action = PdfAction.JavaScript(  js, stamp.Writer);
var ball = new PushbuttonField(stamp.Writer, new Rectangle(x1, y1, x2, y2), "ball" + idx.ToString());
ball.Text = chengyu_def  // tooltip  adobe edge ok  

PdfFormField ballField = ball.Field;
ballField.Action = action;
stamp.AddAnnotation(ballField, 1);