pdf-lib icon indicating copy to clipboard operation
pdf-lib copied to clipboard

Modified Text Field is not showing modified text

Open elcho opened this issue 6 years ago • 4 comments

I am using much of your code to get and set a text field on a pdf template but the text is not showing. I can see that the setting of the 'Ff' field is working as it does render as 'Read Only' but the 'V' field is just blank. I am using create-react-app.

I really appreciate your work!

This is my entire sample code:

import {useDispatch, useSelector} from "react-redux";
import {
    PDFDocument,
    PDFName,
    PDFString,
    PDFArray,
    StandardFonts,
    PDFNumber,
    breakTextIntoLines,
} from 'pdf-lib';


const getPdfDoc = (fileName: string) => {
    return fetch(`/${fileName}`, {
        method: 'GET'
    }).then((res) => res.arrayBuffer())
}

const loadPdf = (pdfBytes: any) => {
    return PDFDocument.load(pdfBytes)
}

const savePdf = (file: PDFDocument) => {
    return file.save()

}

const modify = async(pdfTemplate: any) => {
    console.log('formTemplate::: ', pdfTemplate)

    const pages = pdfTemplate.getPages()
    const firstPage = pages[0]

// Get the width and height of the first page
    const {width, height} = firstPage.getSize()

// Draw a string of text diagonally across the first page
//     firstPage.drawText('This text was added with JavaScript!', {
//         x: 5,
//         y: height / 2 + 300,
//         size: 50,
//         color: rgb(0.95, 0.1, 0.1),
//         rotate: degrees(-45),
//     })


    console.log('Saving modified PDF...');


    // const nameField = findAcroFieldByName(pdfTemplate, 'Name')

    const timesRomanFont = await pdfTemplate.embedFont(StandardFonts.TimesRoman);

    const fieldNames = {
    name: 'Name'
  };

    fillInField(fieldNames.name, 'This field is not visible!', timesRomanFont, false, pdfTemplate)

    return pdfTemplate

}


const fillInField = (fieldName: any, text: any, font: any, multiline = false, pdfDoc: any) => {
    const field = findAcroFieldByName(pdfDoc, fieldName);
    if (!field) throw new Error(`Missing AcroField: ${fieldName}`);
    fillAcroTextField(field, text, font, multiline);
  };

const fillAcroTextField = (acroField: any, text: any, font: any, multiline = false) => {
  const rect = acroField.lookup(PDFName.of('Rect'), PDFArray);
  const width =
    rect.lookup(2, PDFNumber).value() - rect.lookup(0, PDFNumber).value();
  const height =
    rect.lookup(3, PDFNumber).value() - rect.lookup(1, PDFNumber).value();

  const N = multiline
    ? multiLineAppearanceStream(font, text, width, height)
    : singleLineAppearanceStream(font, text, width, height);

    acroField.set(PDFName.of('V'), PDFString.of(text));
    acroField.set(PDFName.of('AP'), acroField.context.obj({ N }));
    acroField.set(PDFName.of('Ff'), PDFNumber.of(1 /* Read Only */));
};


const singleLineAppearanceStream = (font: any, text: any, width: any, height: any) => {
  const size = font.sizeAtHeight(height - 5);
  const lines = [font.encodeText(text)];
  const x = 0;
  const y = height - size;
  return textFieldAppearanceStream(font, size, lines, x, y, width, height);
};

const multiLineAppearanceStream = (font: any, text: any, width: any, height: any) => {
  const size = 12;
  const textWidth = (t: any) => font.widthOfTextAtSize(t, size);
  const lines = breakTextIntoLines(text, [' '], width, textWidth).map((line: any) =>
    font.encodeText(line),
  );
  const x = 0;
  const y = height - size;
  return textFieldAppearanceStream(font, size, lines, x, y, width, height);
};

const textFieldAppearanceStream = (font: any, size: any, lines: any, x: any, y: any, width: any, height: any) => {
    return font.doc.context.obj({
        Type: 'XObject',
        Subtype: 'Form',
        FormType: 1,
        BBox: [0, 0, width, height],
        Resources: {Font: {F0: font.ref}},
    });
}



const getAcroForm = (pdfDoc: any) => {
    return pdfDoc.catalog.lookup(PDFName.of('AcroForm'));
};

const getAcroFields = (pdfDoc: any) => {
    const acroForm = getAcroForm(pdfDoc);
    if (!acroForm) return [];

    const fieldRefs = acroForm.lookupMaybe(PDFName.of('Fields'), PDFArray);
    if (!fieldRefs) return [];

    const fields = new Array(fieldRefs.size());
    for (let idx = 0, len = fieldRefs.size(); idx < len; idx++) {
        fields[idx] = fieldRefs.lookup(idx);
    }
    return fields;
};

const findAcroFieldByName = (pdfDoc: PDFDocument, name: any) => {
    const acroFields = getAcroFields(pdfDoc);
    return acroFields.find((acroField) => {
        const fieldName = acroField.get(PDFName.of('T'));
        return !!fieldName && fieldName.value === name;
    });
};

const SelectedPdfDisplay = (props: any) => {
    const initialState = useSelector((state: any) => state);
    const {initialValues} = props


    const [file, setFile] = useState()
    const [toFetchPdf, setToFetchPdf] = useState()

    const loadPdfFileWithValues = () => {
    getPdfDoc('POA-Template.pdf')
        .then(fetched => loadPdf(fetched))
        .then(res => modify(res))
        .then(pdfDoc => savePdf(pdfDoc))
        .then(res => setFile(res))
}

    const MyIframeDoc = () => {
        let doc = (<h1>Choose a doc</h1>)
        if (file) {
            console.log(file)
            const blob = new Blob([file], {type: "application/pdf"});
            const urlCreator = window.URL || window.webkitURL;
            const imageUrl = urlCreator.createObjectURL(blob);
            return (
                <iframe
                    width="600" height="600"
                    src={imageUrl}>
                </iframe>
            )
        }
        return doc
    }

    return (
        <React.Fragment>
            <h2>{initialValues['applicant_info-first_name']}</h2>
            <MyIframeDoc/>
            <button onClick={() => loadPdfFileWithValues()}>LOAD</button>
        </React.Fragment>
    )
}
export default SelectedPdfDisplay

This is the sample PDF with a 'Name' text field POA-Template.pdf

elcho avatar Jan 22 '20 19:01 elcho

Hello @elcho!

You need to set NeedAppearances to true on your acroform in order to make the field visible:

const {
  // ...,
  PDFBool,
  PDFName,
} = require('pdf-lib');

const modify = async(pdfTemplate: any) => {
    // ...

    fillInField(fieldNames.name, 'This field is not visible!', timesRomanFont, false, pdfTemplate)

    // Add these lines
    const acroForm = getAcroForm(pdfTemplate);
    acroForm.set(PDFName.of('NeedAppearances'), PDFBool.True);

    return pdfTemplate
}

I hope this helps!

Hopding avatar Feb 09 '20 20:02 Hopding

NeedAppearances it's after or before of fillInField?

davidra24 avatar Apr 21 '20 17:04 davidra24

@davidra24 It doesn't matter. You can set it before or after.

Hopding avatar Apr 28 '20 22:04 Hopding

pdf-lib now has form creation and filling APIs that should be used instead of the above example(s). See the form filling JSFiddle for a working example. Additional information is available in the README and API docs. The PDFTextField.setText method is of particular relevance to this issue.

Hopding avatar Sep 16 '20 22:09 Hopding