2013-03-05 123 views
2

如何使用C#中的iTextSharp更改现有PDF文件的字体?使用iTextSharp更改PDF的字体

我想将整个文档字体更改为一个例如Arial

+0

你的期望究竟是什么?只需更改所有文本元素的字体就足够了吗?你知道,如果以前使用的字体与新字体的度量标准不同,字体可能重叠或相距甚远,文本行可能超出正确的文档边界等,那么结果可能看起来非常难看。甚至这种丑陋的解决方案并不总是可能的,因为字符映射信息可能不包含在文档中的字体信息中,在自定义编码的情况下可能使得不可能知道哪个字符是哪个字符。 – mkl 2013-03-05 14:26:34

回答

7

最后我解决了这个问题。 下面的代码将打开一个现有的PDF文件,并将按照我的预期将其所有字体更改为“盲文”。

private static void ChangeFont() 
     { 


      string strFile = @"E:\\xyz.pdf"; 
      string OutputFile = @"E:\\xyz1.pdf"; 
      PdfReader pdfReader = new PdfReader(strFile); 

      //Get first page,Generally we get font information on first page,however we can loop throw pages e.g for(int i=0;i<=pdfReader.NumberOfPages;i++) 
       PdfDictionary cpage = pdfReader.GetPageN(1); 
       if (cpage == null) 
        return; 
       PdfDictionary dictFonts = cpage.GetAsDict(PdfName.RESOURCES).GetAsDict(PdfName.FONT); 
       if (dictFonts != null) 
       { 
        foreach (var font in dictFonts) 
        { 
         var dictFontInfo = dictFonts.GetAsDict(font.Key); 

         if (dictFontInfo != null) 
         { 
          foreach (var f in dictFontInfo) 
          { 
           //Get the font name-optional code 
           var baseFont = dictFontInfo.Get(PdfName.BASEFONT); 
           string strFontName = System.Text.Encoding.ASCII.GetString(baseFont.GetBytes(), 0, 
                          baseFont.Length); 
           // 


           //Remove the current font 
           dictFontInfo.Remove(PdfName.BASEFONT); 
           //Set new font eg. Braille, Areal etc 
           dictFontInfo.Put(PdfName.BASEFONT, new PdfString("Braille")); 
           break; 

          } 
         } 


        } 

      } 

      //Now create a new document with updated font 
      using (FileStream FS = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)) 
      { 
       using (Document Doc = new Document()) 
       { 
        using (PdfCopy writer = new PdfCopy(Doc, FS)) 
        { 
         Doc.Open(); 
         for (int j = 1; j <= pdfReader.NumberOfPages; j++) 
         { 
          writer.AddPage(writer.GetImportedPage(pdfReader, j)); 
         } 
         Doc.Close(); 
        } 
       } 
      } 
      pdfReader.Close(); 

     } 
+0

谢谢。我怎样才能通过使用上面的代码来改变pdf的字体颜色 – Narasappa 2016-03-22 11:11:12

+0

你应该删除'foreach(var f in dictFontInfo)' – isHuman 2016-05-12 09:37:23