Replacing PDF objects
replacestream
JAVA
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package com.itextpdf.samples.sandbox.stamper;
import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfObject;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfStream;
import com.itextpdf.kernel.pdf.PdfWriter;
import java.io.File;
import java.nio.charset.StandardCharsets;
public class ReplaceStream {
public static final String DEST = "./target/sandbox/stamper/replace_stream.pdf";
public static final String SRC = "./src/main/resources/pdfs/hello.pdf";
public static void main(String[] args) throws Exception {
File file = new File(DEST);
file.getParentFile().mkdirs();
new ReplaceStream().manipulatePdf(DEST);
}
protected void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
PdfPage page = pdfDoc.getFirstPage();
PdfDictionary dict = page.getPdfObject();
PdfObject object = dict.get(PdfName.Contents);
if (object instanceof PdfStream) {
PdfStream stream = (PdfStream) object;
byte[] data = stream.getBytes();
String replacedData = new String(data).replace("Hello World", "HELLO WORLD");
stream.setData(replacedData.getBytes(StandardCharsets.UTF_8));
}
pdfDoc.close();
}
}
C#
C#
using System;
using System.IO;
using System.Text;
using iText.Commons.Utils;
using iText.Kernel.Pdf;
namespace iText.Samples.Sandbox.Stamper
{
public class ReplaceStream
{
public static readonly String DEST = "results/sandbox/stamper/replace_stream.pdf";
public static readonly String SRC = "../../../resources/pdfs/hello.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new ReplaceStream().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
PdfPage page = pdfDoc.GetFirstPage();
PdfDictionary dict = page.GetPdfObject();
PdfObject pdfObject = dict.Get(PdfName.Contents);
if (pdfObject is PdfStream)
{
PdfStream stream = (PdfStream) pdfObject;
byte[] data = stream.GetBytes();
String replacedData = JavaUtil.GetStringForBytes(data).Replace("Hello World", "HELLO WORLD");
stream.SetData((Encoding.UTF8.GetBytes(replacedData)));
}
pdfDoc.Close();
}
}
}