Replace string in PDF file using Itext but letter X not replace

后端 未结 3 2084
闹比i
闹比i 2020-12-18 00:12

I\'m trying to replace the content of PDF in one text but the letter \'X\' are not being replaced.

public static void main(String[] args) {

            


        
3条回答
  •  醉梦人生
    2020-12-18 00:29

    I modified the code found a bit and it was working as follows

    public static final String SRC = "C:/tmp/244558.pdf";
    public static final String DEST = "C:/tmp/244558-2.pdf";
    
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new Main().manipulatePdf(SRC, DEST);
    }
    
    public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(src);
        PdfDictionary dict = reader.getPageN(1);
        PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
        PdfArray refs = null;
        if (dict.get(PdfName.CONTENTS).isArray()) {
            refs = dict.getAsArray(PdfName.CONTENTS);
        } else if (dict.get(PdfName.CONTENTS).isIndirect()) {
            refs = new PdfArray(dict.get(PdfName.CONTENTS));
        }
        for (int i = 0; i < refs.getArrayList().size(); i++) {
            PRStream stream = (PRStream) refs.getDirectObject(i);
            byte[] data = PdfReader.getStreamBytes(stream);
            stream.setData(new String(data).replace("Data replace", "Data").getBytes());
        }
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        stamper.close();
        reader.close();
    }
    

提交回复
热议问题