[英]PDF.js Setting a field value?
我希望你們一切都好。 所以我已經使用 Mozilla 的 PDF.js 一段時間了。 我們用它來顯示 PDF forms 以在移動應用程序上填寫。 一切都很好,我只是想實現一個功能,您可以在其中緩存用戶條目,以便他們可以從他們離開的地方恢復。 由於一些原因,我不能只下載 PDF 來保存它,然后在他們要恢復時重新加載它。
本質上,我想存儲所有用戶條目和每個條目的字段 ID,我已經開始工作了,然后當用戶想要恢復時,我希望它加載空的 PDF,然后自動重新填充所有具有緩存條目的字段。
我知道我可以設置單獨的文本字段,但是當我這樣做時它不適用於 annotationStorage 所以當我解析表單時,這些字段被讀取為空白。
我嘗試了以下代碼行,試圖設置一個 ID 為“5R”的字段值
PDFViewerApplication.pdfDocument.annotationStorage.setValue('5R', "Shirboogle");
PDFViewerApplication.pdfDocument.annotationStorage.getAll()['5R'].value = "Shirboogle";
var objs = await PDFViewerApplication.pdfDocument.getFieldObjects();
objs['Address 1 Text Box'][0].value = "Shirboogle";
// and
objs['Address 1 Text Box'][0].defaultValue = "Shirboogle";
// This will actually set the value of the text field, but when I look for it in annotationStorage OR
// getFieldObjects() the value is still unchanged.
document.getElementById('pdfjs_internal_id_5R').value = 'Shapoopsies';
以及許多其他嘗試。 我找遍了,似乎沒有可用的東西,所以如果您有任何想法,請告訴我!
如果有人遇到這個問題,這是我想出的解決方案。 它似乎非常適合我的用例,但可能不足以滿足所有情況。 我想我至少會分享我的工作。
它基本上手動設置所有內容。 仍然有一些 UI 元素我需要做一個 if 語句來設置,但無論如何。 這是我的代碼。 祝你好運:)
function getFieldValue(id) {
return PDFViewerApplication.pdfDocument.annotationStorage.getAll()[id].value;
}
async function getFieldObjById(id) {
var objs = await PDFViewerApplication.pdfDocument.getFieldObjects();
for(var i=0; i<Object.values(objs).length; i++) {
if(Object.values(objs)[i][0].id == id) {
return Object.values(objs)[i][0];
}
}
}
async function setFieldValue(id, val) {
var fElementId = "pdfjs_internal_id_" + id;
var fObject = await getFieldObjById(id);
var objType = fObject.type;
// Depending on the element type we set the value accordingly.
if(objType == 'text') {
document.getElementById(fElementId).value = val;
PDFViewerApplication.pdfDocument.annotationStorage.setValue(id, {value: val});
}
else if(objType == 'checkbox') {
document.getElementById(fElementId).checked = val;
PDFViewerApplication.pdfDocument.annotationStorage.setValue(id, {value: val});
}
else if(objType == 'combobox') {
document.getElementById(fElementId).selectedIndex = val;
var sLabel = document.getElementById(fElementId).options[document.getElementById(fElementId).selectedIndex].label;
PDFViewerApplication.pdfDocument.annotationStorage.setValue(id, {value: sLabel});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.