field_merge: Example code of Early Access iText(how to fill PDF form with iTextSharp)

本示例代码展示了如何使用iTextSharp库在PDF文件中进行字段合并及展平操作。通过命令行参数接收输入PDF文件路径、输出PDF文件路径及待设置的字段值。代码首先读取源PDF文件,然后利用PdfStamper对象将字段值写入并选择是否展平表单字段。
using  System;
using  iTextSharp.text;
using  iTextSharp.text.pdf;
using  System.IO;
public   class  field_merge
{
    
    
private   static   void   usage()
    {
        
        System.Console.Out.WriteLine(
" Field merging and flattening " );
        System.Console.Out.WriteLine(
" usage: field_merge [-f] infile_pdf outfile_pdf [[name1=value1]dot.gif[namex=valuex]] " );
        System.Console.Out.WriteLine(
"     -f - flatten the fields " );
    }
    

    [STAThread]
    
public   static   void   Main( string [] args)
    {
        
if  (args.Length  <   2 )
        {
            usage();
            
return  ;
        }
        
int  idx  =   0 ;
        
if  (args[ 0 ].Equals( " -f " ))
            
++ idx;
        
if  (args.Length  -  idx  <   2 )
        {
            usage();
            
return  ;
        }
        
string  in_pdf  =  args[idx];
        
string  out_pdf  =  args[idx  +   1 ];
        
try
        {
            PdfReader reader 
=   new  PdfReader(in_pdf);
            PdfStamper stamp 
=   new  PdfStamper(reader,  new  FileStream(out_pdf, FileMode.Create));
            AcroFields form 
=  stamp.AcroFields;
            
for  ( int  k  =  idx  +   2 ; k  <  args.Length;  ++ k)
            {
                
string  t  =  args[k];
                
int  x  =  t.IndexOf((System.Char)  ' = ' );
                
if  (x  >   0 )
                {
                    
string  field  =  t.Substring( 0 , (x)  -  ( 0 ));
                    
string  value_Renamed  =  t.Substring(x  +   1 );
                    form.SetField(field, value_Renamed);
                }
            }
            
if  (idx  >   0 )
                stamp.FormFlattening
= ( true );
            stamp.Close();
            System.Console.Out.WriteLine(
" Done. " );
        }
        
catch  (System.Exception e)
        {
            System.Console.Error.WriteLine(e.Message);
        }
    }
}
 
本文转自 RubyPdf 的中文博客博客园博客,原文链接: http://www.cnblogs.com/hardrock/archive/2006/07/18/453494.html /,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值