2013-03-05 126 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