如何使用pdfbox填写特定字体的PDF表格?

时间:2017-04-27 13:50:38

标签: pdf pdfbox

我正在尝试填写pdf表单,我可以通过PDFBox库使用以下方法填写它。

val pdf: PDDocument = PDDocument.load(file)
pdf.setAllSecurityToBeRemoved(true)
val docCatalog: PDDocumentCatalog = pdf.getDocumentCatalog
val acroForm: PDAcroForm = docCatalog.getAcroForm

def populateFields(inputJson: String, targetPdfPath: String): Unit = {
    val valueMap: Array[Field] = gson.fromJson(inputJson, classOf[Array[Field]])
    valueMap.foreach((field) => {
      val pdField: PDField = acroForm.getField(field.name)

      if (pdField != null) {
        pdField.setValue(field.value)
      } else {
        println(s"No field with name ${field.name}")
      }
    })

    pdf.save(targetPdfPath)
    pdf.close()
  }

唯一的问题是,在填写pdf之前,我没有看到任何设置字体的选项。你能帮帮我吗?

1 个答案:

答案 0 :(得分:2)

您可以使用这些方法来实现它(请注意,您必须使用PDFBox 1.8.15,而不是较新的2.0)。

// Set the field with custom font.
private void setField(String name, String value, String fontSource) throws IOException {
    PDDocumentCatalog docCatalog;
    PDAcroForm acroForm;
    PDField field;
    COSDictionary dict;
    COSString defaultAppearance;
    docCatalog = pdfTemplate.getDocumentCatalog();
    acroForm = docCatalog.getAcroForm();
    field = acroForm.getField(name);
    dict = (field).getDictionary();
    defaultAppearance = (COSString) dict.getDictionaryObject(COSName.DA);

    if (defaultAppearance != null)
    {
        dict.setString(COSName.DA, "/" + fontName + " 10 Tf 0 g");
        if (name.equalsIgnoreCase("Field1")) {
            dict.setString(COSName.DA, "/" + fontName + " 12 Tf 0 g");
        }
    }
    if (field instanceof PDTextbox)
    {
        field = new PDTextbox(acroForm, dict);
        (field).setValue(value);
    }
}

// Set the field with custom font.
private List<String> prepareFont(PDDocument _pdfDocument, List<PDFont> fonts) {
    PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
    PDAcroForm acroForm = docCatalog.getAcroForm();

    PDResources res = acroForm.getDefaultResources();
    if (res == null)
        res = new PDResources();

    List<String> fontNames = new ArrayList<>();
    for (PDFont font: fonts)
    {
        fontNames.add(res.addFont(font));
    }

    acroForm.setDefaultResources(res);
    return fontNames;
}

// Set the field with custom font.
private PDFont loadTrueTypeFont(PDDocument _pdfDocument, String resourceName) throws IOException
{
    return PDTrueTypeFont.loadTTF(_pdfDocument, new File(resourceName));
}

现在,您只需使用字段名称,要插入的值和一个字符串(该字符串是您要使用的TTF字体的路径)来获取方法setField

希望有帮助!