c# – 在iTextSharp中设置元数据

前端之家收集整理的这篇文章主要介绍了c# – 在iTextSharp中设置元数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个应用程序,我使用iTextSharp库.

我也在阅读曼宁的iText,所以我可以获得参考.

在第12章中,它具有以下代码来更改Java中的元数据.

PdfReader reader = new PdfReader(src);
PdfStamper stamper =
new PdfStamper(reader,new FileOutputStream(dest));
HashMap<String,String> info = reader.getInfo();
info.put("Title","Hello World stamped");
info.put("Subject","Hello World with changed Metadata");
info.put("Keywords","iText in Action,PdfStamper");
info.put("Creator","Silly standalone example");
info.put("Author","Also Bruno Lowagie");
stamper.setMoreInfo(info);
stamper.close();

我怎样才能在C#中做同样的事情?

解决方法

从Java到C#的转换通常非常简单.按照惯例,Java属性使用get和set前缀,因此要转换为C#,您只需要删除前缀并将其转换为.Net getter / setter调用. getInfo()变为Info,setMoreInfo(info)变为MoreInfo = info.然后,您只需将本机Java类型转换为其等效的C#类型.在这种情况下,Java FileOutputStream变为.Net FileStream和HashMap< String,String>成为字典< String,String>.

最后,我更新了代码以反映最近对iTextSharp的更改,现在(从5.1.1.0开始)实现了IDisposable.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender,EventArgs e)
        {
            string workingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string inputFile = Path.Combine(workingFolder,"Input.pdf");
            string outputFile = Path.Combine(workingFolder,"Output.pdf");

            PdfReader reader = new PdfReader(inputFile);
            using(FileStream fs = new FileStream(outputFile,FileMode.Create,FileAccess.Write,FileShare.None)){
                using (PdfStamper stamper = new PdfStamper(reader,fs))
                {
                    Dictionary<String,String> info = reader.Info;
                    info.Add("Title","Hello World stamped");
                    info.Add("Subject","Hello World with changed Metadata");
                    info.Add("Keywords",PdfStamper");
                    info.Add("Creator","Silly standalone example");
                    info.Add("Author","Also Bruno Lowagie");
                    stamper.MoreInfo = info;
                    stamper.Close();
                }
            }

            this.Close();
        }
    }
}

猜你在找的C#相关文章