2012-05-01 3 views
0

itextsharp를 사용하여 PDF 양식 필드를 채우는 응용 프로그램이 있습니다.itextsharp를 사용한 양식 필드 값 밑줄

필드 값에 밑줄을 긋기 위해 고객으로부터 새로운 요구 사항이 있습니다.

본 사이트의 질문에 대한 답변을 비롯하여 많은 게시물을 읽었지만이를 수행 할 방법을 찾지 못했습니다.

현재 내 코드는 다음을 수행합니다

  1. 가 PDFStamper 인스턴스
  2. 를 작성합니다 AcroFields.SetFieldRichValue() 메소드를 사용하여 필드 값을 설정 stamper.AcroFields 속성
  3. 를 사용하여 양식 필드를 가져옵니다.

하지만 PDF를 열 때 입력란이 비어 있습니다.

필드가 PDF 자체에서 서식있는 텍스트로 설정되어 있는지 확인했습니다.

내가 뭘 잘못하고 있는지 알기!

   FileStream stream = File.Open(targetFile, FileMode.Create);          
       var pdfStamper = new PdfStamper(new PdfReader(sourceFile), stream);      

       // Iterate the fields in the PDF 
       foreach (var fieldName in pdfStamper.AcroFields.Fields.Keys) 
       {      
        // Get the field value of the current field 
        var fieldValue = "<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\" xfa:contentType=\"text/html\" xfa:APIVersion=\"Acrobat:8.0.0\" xfa:spec=\"2.4\"><p style=\"text-align:left\"><b><i>Here is some bold italic text</i></b></p><p style= \"font-size:16pt\">This text uses default text state parameters but changes the font size to 16.</p></body>" 

        // Set the field value 
        if (String.IsNullOrEmpty(fieldValue) == false) 
        { 
         pdfStamper.AcroFields.SetFieldRichValue(key, fieldValue); 
        } 
       } 

편집 :

내가 (질문에 마크 Storer의 게시물을 기반으로 내 코드를 수정 한

http://stackoverflow.com/questions/1454701 여기

내 코드의 snnipest입니다/rich-text-to-an-acrofield-in-itextsharp)를 사용합니다. ....

어떤 아이디어

 // Create reader to read the source file 
     var reader = new PdfReader(sourceFile); 

     // Create a stream for the generated file 
     var stream = File.Open(targetFile, FileMode.Create); 

     // Create stamper to generate the new file 
     var pdfStamper = new PdfStamper(reader, stream); 

     // Field name and value 
     var fieldName = "myfield"; 
     var fieldValue = "<?xml version=\"1.0\"?><body xfa:APIVersion=\"Acroform:2.7.0.0\" xfa:spec=\"2.1\" xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><p dir=\"ltr\" style=\"margin-top:0pt;margin-bottom:0pt;font-family:Helvetica;font-size:12pt\"><b>write line1 bold</b></p</body>"; 

     // Output stream for the temporary file that should contain the apearance of the field 
     var msOutput = new FileStream(@"d:\temp.pdf", FileMode.Create); 

     // string reader to read the field value 
     var textReader = new StringReader(fieldValue); 

     // Create new document 
     var document = new Document(pdfStamper.AcroFields.GetFieldPositions(fieldName)[0].position); 

     // writer for the new doucment 
     var writer = PdfWriter.GetInstance(document, msOutput); 

     // Open the document     
     document.Open(); 

     // Get elements to append to the doucment 
     var list = HTMLWorker.ParseToList(textReader, null); 

     // Append elements to the doucment 
     foreach (var element in list) 
     { 
      document.Add(element); 
     }           

     // close the documnet 
     document.Close();        

     // Append push button that contains the generated content as its apearance 
     // this approach is based on the suggestion from Mark storer that can be found in: 
     // http://stackoverflow.com/questions/1454701/adding-rich-text-to-an-acrofield-in-itextsharp 
     var button = new PushbuttonField(pdfStamper.Writer, pdfStamper.AcroFields.GetFieldPositions(fieldName)[0].position, fieldName + "_") 
          { 
           Layout = PushbuttonField.LAYOUT_ICON_ONLY, 
           BackgroundColor = null, 
           Template = pdfStamper.Writer.GetImportedPage(new PdfReader(targetFile, 1) 
          }; 
      pdfStamper.AddAnnotation(button.Field, 1);     

     pdfStamper.FormFlattening = true; 
     pdfStamper.Close(); 
     pdfStamper.Dispose(); 

하지만 지금 문제는 임시 문서에 내용이 없다는 것입니다 : 새로운 코드는?

+0

이 문제지만 당신은 또한에 작성 스트림에서 읽고 있다면 나도 몰라 : 여기

은 내가 사용하는 코드입니다. 코드의 두 번째 줄은'targetFile'을 열고, 그 아래쪽을 향해 여전히 열려있는 동안 읽으려고합니다. 귀하의 코드를 실행할 때 실제로 그것을 시도하는 동안 예외가 발생합니다. –

+0

아니요 - 문제가되지 않습니다. 문제가 코드에서 더 일찍 시작되기 때문에 내가 말하는 내용과 관련이 있는지 확인하지 않았습니다. - 코드에서 document.Close()를 호출 한 후 내용이 있어야하는 d : \ temp.pdf 파일을 만듭니다. 이 코드 줄 이후에는 임시 파일이 여전히 비어 있으며 이유를 알 수 없습니다. 이 문제를 해결 한 후에 버튼의 템플릿 속성에 임시 파일 내용을 적용하는 것이 훨씬 간단하다고 가정합니다. –

+0

사용중인 iTextSharp의 버전은 무엇입니까? –

답변

0

작은 트릭으로 해결할 수있었습니다. ColumnText 요소 안의 Anchor (하이퍼 링) 요소를 사용하여 양식 필드 위에 배치했습니다. 앵커는 기본적으로 밑줄로 표시됩니다. 사용자가 앵커에서 마우스를 가리키면 손 모양 표식을 피하기 위해 앵커의 "참조"속성을 null로 설정합니다.

// Create reader 
var reader = new PdfReader(sourceFilePathAndName); 

// Create stream for the target file 
var stream = File.Open(targetFilePathAndName, FileMode.Create); 

// Create the stamper 
var pdfStamper = new PdfStamper(reader, stream); 

const string fieldName = "MyField";  

// Get the position of the field 
var targetPosition = pdfStamper.AcroFields.GetFieldPositions(fieldName)[0].position; 

// Set the font 
var fontNormal = FontFactory.GetFont("Arial", 16, Font.UNDERLINE, BaseColor.BLACK); 

// Create the anchor 
var url = new Anchor("some default text", fontNormal) { Reference = null }; 

// Create the element that will contain the anchor and allow to position it anywhere on the document 
var data = new ColumnText(pdfStamper.GetOverContent(1)); 

// Add the anchor to its container 
data.SetSimpleColumn(url, targetPosition.Left, targetPosition.Bottom, targetPosition.Right, targetPosition.Top, 0, 0); 

// Write the content to the document 
data.Go(); 

pdfStamper.FormFlattening = true; 
pdfStamper.Close(); 
pdfStamper.Dispose(); 
0

위의 코드는 거의 400 줄입니다. 앞으로는 모든 것을 간단하고 재현성있는 테스트 케이스로 추출하십시오.

SetFieldRichValue를 사용하여 당신은 또한 falsePdfStamperAcroFields.GenerateAppearances 속성을 설정해야합니다

stamper.AcroFields.GenerateAppearances = false; 

당신은 몇 가지주의와 다른 해결 방법과 함께이 here에 대한 자세한 내용을보실 수 있습니다.

+0

입니다. 나는 링크를 점검 할 것이다. 코드의 길이를 줄이기 위해 내 질문을 업데이트했습니다 –

+2

내 문제를 해결하지 못했습니다 ... –

관련 문제