简体   繁体   中英

How to add specific number of bytes to pdf file using itextsharp

I am creating a pdf file using iTextsharp. Minimum size of the pdf file should be 1024 bytes. Is there any way to add specific chunk data to file. I tried adding 1024 blank characters. But its not working.

You can add a PDF stream object with a stream content size of your choice:

Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, output);
...
byte[] bytes = new byte[1024];
for (int i = 0; i < bytes.Length; i++)
    bytes[i] = (byte)(i & 0xff);
PdfStream pdfStream = new PdfStream(bytes);
writer.AddToBody(pdfStream, false);

This will add a genuine PDF stream object containing the given bytes to the PDF. Compression is not applied.

The added number of bytes is not exactly merely the array length, there is a bit of overhead for the PDF stream itself and its entry in the cross references.

Alternatively you can directly add bytes to the underlying stream directly:

Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, output);
...
byte[] bytes = new byte[1024];
for (int i = 0; i < bytes.Length; i++)
    bytes[i] = (byte)(0x0a);
writer.Os.Write(bytes, 0, bytes.Length);

The added number of bytes is (nearly) exactly the array length; merely the offset of the cross references might now require an additional digit (eg without the addition four digits 9000 , with it five digits 10024 ).

You should be more cautious here, though, and use a byte array of only white spaces or a comment or something similarly harmless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM