使用iTextSharp的(或C#PDF库),如何打开一个PDF,更换一些文本,然后再保存呢?

问题描述 投票:7回答:3

使用iTextSharp的(或C#PDF库),我需要打开一个PDF,更换与实际值的一些占位符文本,并返回它作为一个byte []。

有人建议如何做到这一点?我有一个看看iText的文档和不能找出哪里开始。到目前为止,却困如何从PDFReader Document对象获取源PDF,我相信我可能接近这个错误的方式。

非常感谢

c# pdf itextsharp acrobat
3个回答
5
投票

最后,我用PDFescape打开我现有的PDF文件,并将其放置在我需要把我的田某种形式的字段,然后再次将其保存到我的创建PDF文件。

http://www.pdfescape.com

后来我发现关于如何更换表单字段此博客条目:

http://www.johnnycode.com/blog/2010/03/05/using-a-template-to-programmatically-create-pdfs-with-c-and-itextsharp/

所有的作品很好!下面的代码:

public static byte[] Generate()
{
  var templatePath = HttpContext.Current.Server.MapPath("~/my_template.pdf");

  // Based on:
  // http://www.johnnycode.com/blog/2010/03/05/using-a-template-to-programmatically-create-pdfs-with-c-and-itextsharp/
  var reader = new PdfReader(templatePath);
  var outStream = new MemoryStream();
  var stamper = new PdfStamper(reader, outStream);

  var form = stamper.AcroFields;
  var fieldKeys = form.Fields.Keys;

  foreach (string fieldKey in fieldKeys)
  {
    if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldA")
      form.SetField(fieldKey, "1234");
    if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldB")
      form.SetField(fieldKey, "5678");
  }

  // "Flatten" the form so it wont be editable/usable anymore  
  stamper.FormFlattening = true;  

  stamper.Close();
  reader.Close();

  return outStream.ToArray();
}

1
投票

不幸的是我一直在寻找类似的东西,不能弄明白。下面是关于据我得到的,也许你可以使用它作为一个起点。问题是,PDF不实际保存的文本,而是使用查找表和其他一些神秘的巫术。此方法读取该网页的字节值并尝试转换为字符串,但据我可以告诉它只能做英文而错过了一些特殊字符,所以我放弃了我的项目,并继续前行。

string contents = string.Empty();
Document doc = new Document();
PdfReader reader = new PdfReader("pathToPdf.pdf");
using (MemoryStream memoryStream = new MemoryStream())
{

    PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
    doc.Open();
    PdfContentByte cb = writer.DirectContent;
    for (int p = 1; p <= reader.NumberOfPages; p++)
    {
        // add page from reader
        doc.SetPageSize(reader.GetPageSize(p));
        doc.NewPage();

        // pickup here something like this:
        byte[] bt = reader.GetPageContent(p);
        contents = ExtractTextFromPDFBytes(bt);

        if (contents.IndexOf("something")!=-1)
        {
            // make your own pdf page and add to cb (contentbyte)

        }
        else
        {
            PdfImportedPage page = writer.GetImportedPage(reader, p);
            int rot = reader.GetPageRotation(p);
            if (rot == 90 || rot == 270)
                cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(p).Height);
            else
                cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0);
        }
    }
    reader.Close();
    doc.Close();
    File.WriteAllBytes("pathToOutputOrSamePathToOverwrite.pdf", memoryStream.ToArray());

这是从this site拍摄。

private string ExtractTextFromPDFBytes(byte[] input) 
{ 
    if (input == null || input.Length == 0) return ""; 

     try 
     { 
         string resultString = ""; 

         // Flag showing if we are we currently inside a text object 
         bool inTextObject = false; 

         // Flag showing if the next character is literal  
         // e.g. '\\' to get a '\' character or '\(' to get '(' 
         bool nextLiteral = false; 

         // () Bracket nesting level. Text appears inside () 
         int bracketDepth = 0; 

         // Keep previous chars to get extract numbers etc.: 
         char[] previousCharacters = new char[_numberOfCharsToKeep]; 
         for (int j = 0; j < _numberOfCharsToKeep; j++) previousCharacters[j] = ' '; 


          for (int i = 0; i < input.Length; i++) 
          { 
              char c = (char)input[i]; 

              if (inTextObject) 
              { 
                  // Position the text 
                  if (bracketDepth == 0) 
                  { 
                      if (CheckToken(new string[] { "TD", "Td" }, previousCharacters)) 
                      { 
                          resultString += "\n\r"; 
                      } 
                      else 
                      { 
                          if (CheckToken(new string[] { "'", "T*", "\"" }, previousCharacters)) 
                          { 
                               resultString += "\n"; 
                           } 
                           else 
                           { 
                               if (CheckToken(new string[] { "Tj" }, previousCharacters)) 
                                { 
                                    resultString += " "; 
                                } 
                            } 
                        } 
                    }

                    // End of a text object, also go to a new line. 
                    if (bracketDepth == 0 && 
                        CheckToken(new string[] { "ET" }, previousCharacters)) 
                    { 

                        inTextObject = false; 
                        resultString += " "; 
                   } 
                   else 
                   { 
                        // Start outputting text 
                        if ((c == '(') && (bracketDepth == 0) && (!nextLiteral)) 
                        { 
                            bracketDepth = 1; 
                        } 
                        else 
                        { 
                            // Stop outputting text 
                            if ((c == ')') && (bracketDepth == 1) && (!nextLiteral)) 
                            { 
                                 bracketDepth = 0; 
                            } 
                            else 
                            { 
                                // Just a normal text character: 
                                if (bracketDepth == 1) 
                                { 
                                    // Only print out next character no matter what.  
                                    // Do not interpret. 
                                    if (c == '\\' && !nextLiteral) 
                                    { 
                                        nextLiteral = true; 
                                    } 
                                    else 
                                    { 
                                        if (((c >= ' ') && (c <= '~')) || 
                                            ((c >= 128) && (c < 255))) 
                                        { 
                                            resultString += c.ToString(); 
                                        } 

                                        nextLiteral = false; 
                                    } 
                                } 
                            } 
                        } 
                    } 
                } 

                // Store the recent characters for  
                // when we have to go back for a checking 
                for (int j = 0; j < _numberOfCharsToKeep - 1; j++) 
                { 
                    previousCharacters[j] = previousCharacters[j + 1]; 
                } 
                previousCharacters[_numberOfCharsToKeep - 1] = c; 

                // Start of a text object 
                if (!inTextObject && CheckToken(new string[] { "BT" }, previousCharacters)) 
                { 
                    inTextObject = true; 
                } 
            } 
        return resultString; 
    } 
    catch 
    { 
        return ""; 
     } 
} 

 private bool CheckToken(string[] tokens, char[] recent) 
 { 
     foreach (string token in tokens) 
     { 
         if ((recent[_numberOfCharsToKeep - 3] == token[0]) && 
           (recent[_numberOfCharsToKeep - 2] == token[1]) && 
           ((recent[_numberOfCharsToKeep - 1] == ' ') || 
           (recent[_numberOfCharsToKeep - 1] == 0x0d) || 
           (recent[_numberOfCharsToKeep - 1] == 0x0a)) && 
           ((recent[_numberOfCharsToKeep - 4] == ' ') || 
           (recent[_numberOfCharsToKeep - 4] == 0x0d) || 
           (recent[_numberOfCharsToKeep - 4] == 0x0a))) 
           { 
               return true; 
           } 
    }
    return false; 
} 

0
投票

我这里有一个python脚本替换PDF中的一些文字:

import re
import sys
import zlib

# Module to find and replace text in PDF files
#
# Usage:
#   python pdf_replace.py <input_filename> <text_to_find> <text_to_replace> <output_filename>
#
# @author Ionox0

input_filename = sys.argv[1]
text_to_find = sys.argv[2]
text_to_replace = sys.argv[3]
output_filename sys.argv[4]

pdf = open(input_filename, "rb").read()

# Create a copy of the PDF content to make edits to
pdf_copy = pdf[0:]

# Search for stream objects with text to replace
stream = re.compile(r'.*?FlateDecode.*?stream(.*?)endstream', re.S)

for s in stream.findall(pdf):
    s = s.strip('\r\n')

    try:
        text = zlib.decompress(s)

        if text_to_find in text:
            print('Found match:')
            print(text)

            text = text.replace(text_to_find, text_to_replace)
            pdf_copy = pdf_copy.replace(s, zlib.compress(text))
    except:
        pass

with open(output_filename, 'wb') as out:
    out.write(pdf_copy)