2013-03-11 5 views
1

Я пытаюсь использовать iText, чтобы заполнить цвет текстового поля. Я попытался setfieldproperty, и он не работает с атрибутом bgcolor или fill color. То, что я ищу это свойство текстового поля, чтобы установить, как это будет наложен существующий текст или изображениеИспользование iText для заполнения поля текстового поля

Я попробовал пару случаев в конце ..

' Create a new PDF reader based on the PDF template document 
    Dim pdfReaderBG As PdfReader = New PdfReader(pdfTemplate) ' Page of Fields 
    Dim pdfReaderFG As PdfReader = New PdfReader(pdfExisting) ' Image from CD Image 

    'Create the stream for the new PDF Document with the BackGround PDf 
    Dim writer As PdfStamper = New PdfStamper(pdfReaderBG, New FileStream("c:\temp\CDs\newMerge.pdf", FileMode.Create)) 

    'Get all the content of the page 
    Dim content_Byte As PdfContentByte = writer.GetUnderContent(1) 

    'Then get the Other PDF to overlay the other 
    Dim mark_page As PdfImportedPage = writer.GetImportedPage(pdfReaderFG, 1) 

    If (mark_page.Width > mark_page.Height) Then 'Check to see if it is in Landscape 
     content_Byte.AddTemplate(mark_page, 0, -1, 1, 0, 0, mark_page.Width) 
    Else 
     'Then add the content to the new page over the Image 
     content_Byte.AddTemplate(mark_page, 0, 0) 
    End If 

    Dim formFields As AcroFields = writer.AcroFields 

    formFields.SetFieldProperty("cd28", "borderColor", BaseColor.GREEN, Nothing) 
    'content_Byte.te(BaseColor.PINK) 

    **formFields.SetFieldProperty("cd28", "backgroundcolor", BaseColor.YELLOW, Nothing) 
    'formFields.setfieldproperty("cd28") ' SetFieldProperty("cd28", "bgColor", BaseColor.WHITE, Nothing)** 

Я просто хочу изменить цвет фона одного текстового поля

Когда вы вручную редактируете текстовое поле в документе. Вкладка свойств свойств. У него есть свойство для цвета заливки и цвета границы Я могу сделать цвет границы .. Я не могу изобразить свойство заливки цвета в коде ..

+0

я добавил выше код – theApeman

+0

опция BorderColor работает ... – theApeman

+0

OK обновления. Я пробовал печатать и сплющивать документ .. он не сохраняет цвет границы ... есть ли способ сделать это ??? – theApeman

ответ

2

Цвет фона хранится в виджет-видоискателе поле формы под ключом MK (PDF Spec 12.5.6.19)

Ниже приведен пример кода, который устанавливает цвет фона двумя различными способами. Первый блок создает новый PDF-файл и добавляет к нему поле формы. После этого вы можете просто установить свойство MKBackgroundColor на FormField, и все готово. Второй блок редактирует PDF-файл первого блока, получает именованное поле, создает новый словарь, добавляет к нему цвет и назначает его виджету поля (уничтожая любые существующие записи MK в процессе).

Первый блок кода - гораздо более простой маршрут. См. Комментарии в коде для получения дополнительной информации.

''//File to output 
    Dim TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf") 
    Dim Test2File = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test2.pdf") 

    ''//Standard iTextSharp setup, nothing special 
    Using FS As New FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None) 
     Using Doc As New Document() 
      Using writer = PdfWriter.GetInstance(Doc, FS) 
       Doc.Open() 

       ''//Add a generic paragraph 
       Doc.Add(New Paragraph("Hello")) 

       ''//Create our text field 
       Dim TF As New iTextSharp.text.pdf.TextField(writer, New Rectangle(50, 650, 250, 600), "FirstName") 

       ''//Get the raw form field 
       Dim FF = TF.GetTextField() 

       ''//Sat the background color 
       FF.MKBackgroundColor = BaseColor.RED 

       ''//Add it to the document 
       writer.AddAnnotation(FF) 
       Doc.Close() 
      End Using 
     End Using 
    End Using 

    ''//Read the file above 
    Dim R As New PdfReader(TestFile) 
    ''//Create a new output file 
    Using FS As New FileStream(Test2File, FileMode.Create, FileAccess.Write, FileShare.None) 
     ''//Bind a stamper 
     Using stamper As New PdfStamper(R, FS) 

      ''//Get all of the fields 
      Dim Fields = stamper.AcroFields.Fields 

      ''//Get our specific field created above 
      Dim FF = stamper.AcroFields.GetFieldItem("FirstName") 

      ''//Color to use for the background 
      Dim ColorBase = BaseColor.GREEN 

      ''//The background color is a part of the display widget's MK property 
      ''//This example is going to erase any existing ones and just create a new one 
      Dim NewMK As New PdfDictionary(PdfName.MK) 
      ''//Put our backgroun and the RGB values into the MK dictionary 
      NewMK.Put(PdfName.BG, New PdfArray({ColorBase.R, ColorBase.G, ColorBase.B})) 

      ''//Get the actual widget for the field 
      Dim W = FF.GetWidget(0) 
      ''//Set the MK value 
      W.Put(PdfName.MK, NewMK) 

      ''//Save and close 
      stamper.Close() 
     End Using 
    End Using 
+0

Спасибо Крису ... Я попробую это позже .. это похоже на то, что я искал – theApeman

+0

Это сработало ... единственное, что теперь, когда текст вращается .. Мне нужно это на 270. – theApeman

+0

Вы должны уметь чтобы избавиться от всего экземпляра 'NewMK' и сделать что-то вроде' W.GetAsDict (PdfName.MK) .Put (PdfName.BG, New PdfArray ({ColorBase.R, ColorBase.G, ColorBase.B})). Это должно сохранить существующее вращение виджета. –

Смежные вопросы