如何在Adobe Acrobat DC中的JavaScript脚本中定义字符串的编码

问题描述 投票:0回答:1

我使用Adobe Acrobat DC中的JavaScript来批量填写可填写的PDF表格,并在制表符分隔的文件中为每个条目创建副本。

该文件位于UTF-8中,打开文本文件时,字符(捷克语)č和š可见。

[另外,当我手动将字符复制并粘贴到PDF表单中时,我也可以看到字符。

但是,当我运行JavaScript操作时,这些字符未正确插入。而是有一些奇怪的字符。

JavaScript是这样的:

var fileName = "/Users/username/tmp/data.txt";  // the tab delimited text file containing the data
var outputDir = "/Users/username/tmp/";    // make sure this ends with a '/'

var err = 0;
var idx = 0;
while (err == 0) {
    err = this.importTextData(fileName, idx); // imports the next record
    if (err == -1)
        app.alert("Error: Cannot Open File");
    else if (err == -2)
        app.alert("Error: Cannot Load Data");
    // else if (err == -3)
        // We are not reporting this error because it does
        // indicate the end of our data table: We've exhausted
        // all rows in the data file and therefore are done with
        // processing the file. Time to exit this loop. 
        // app.alert("Error: Invalid Row");
    else if (err == 1)
        app.alert("Warning: User Cancelled File Select");
    else if (err == 2)
        app.alert("Warning: User Cancelled Row Select");
    else if (err == 3)
        app.alert("Warning: Missing Data");
    else if (err == 0) {
        this.saveAs(outputDir + this.getField("Text1").value + "_" + this.getField("Text2").value + ".pdf"); // saves the file
        idx++;
    }
}```

Please note that credit for this JavaScript goes to Karl Heinz Kremer from http://khkonsulting.com/2015/10/batch-import-excel-data-into-pdf-forms/


javascript utf-8 adobe acrobat
1个回答
1
投票

出于多种原因,我真的不喜欢Doc.importTextData功能。对编码的控制只是其中之一。相反,请使用Util.readFileIntoStream(),然后使用Util.stringFromStream(),您可以在其中设置编码,然后将文本解析为行,然后将其解析为字段以填充表格]

由于使用路径保存文件的安全性限制,必须从Acrobat JavaScript控制台运行此脚本。 XLS中的列名称和PDF中的字段名称必须完全匹配。导出到XLS到CSV UTF-8。字段名称区分大小写。 PDF中没有相应字段的列将被忽略。

使用:打开表单模板,然后从控制台运行此代码。

console.clear();
var baseFileName = this.documentFileName.replace(".pdf", "");
var fileStream = util.readFileIntoStream();
var fileString = util.stringFromStream(fileStream, "utf-8");

var rows = fileString.split("\n");
var columns = rows[0].split(",");

for (var i = 1; i < rows.length; i++) {
    var row = rows[i].split(",");
    for (var j = 0; j < columns.length; j++) {
        var fieldName = columns[j].replace(/[^\x00-\x7F]/g, "");
        var value = row[j];
        console.println(fieldName+": "+value)
        try {
            var field = this.getField(fieldName);
            field.value = value;
        }
        catch (err) { }
    }
    // Customize this area for your own needs. This area builds the output filename.
    var outputFileName = this.getField("last_name").value + "_" + this.getField("first_name").value;
    // Save the file as a copy so that the template can be reused 
    this.saveAs({
        cPath: outputFileName+ ".pdf",
        bCopy: true
    })
}
this.resetForm();

我发布了一个工作示例文件here

© www.soinside.com 2019 - 2024. All rights reserved.