Set Metadata in iTextSharp

后端 未结 3 1586
说谎
说谎 2020-12-18 03:28

I am developing an application and i use the iTextSharp library.

I am also reading the iText in action from Manning so i can get references.

In Chapter 12 it

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 03:51

    I just made this one after searching the right place in the watch window of the PdfWriter object, it changes the "PDF Creator" in the PDF as it is not accessible by default:

    private static void ReplacePDFCreator(PdfWriter writer)
        {
            Type writerType = writer.GetType();
            PropertyInfo writerProperty = writerType.GetProperties(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).Where(p => p.PropertyType == typeof(PdfDocument)).FirstOrDefault();
    
            PdfDocument pd =  (PdfDocument)writerProperty.GetValue(writer);
            Type pdType = pd.GetType();
            FieldInfo infoProperty = pdType.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).Where(p => p.Name == "info").FirstOrDefault();
            PdfDocument.PdfInfo pdfInfo = (PdfDocument.PdfInfo)infoProperty.GetValue(pd);
    
            PdfString str = new PdfString("YOUR NEW PDF CREATOR HERE");
            pdfInfo.Remove(new PdfName("Producer"));
            pdfInfo.Put(new PdfName("Producer"), str);
        }
    

    I got a suggestion from "@yannic-donot-text" and it is way much cleaner!:

    private static void ReplacePDFCreator(PdfWriter writer)
        {
           writer.Info.Put(new PdfName("Producer"), new PdfString("YOUR NEW PDF CREATOR HERE"));
        }
    

    I tought it was only archievable by reflection but I appreciate the collaboration of more educated persons :)

    Thx!

提交回复
热议问题