Controlling the font of the content of an HTML Table in iTextSharp - itext

I am using the most recent DLLs and trying to render HTML fragments into a PDF document using the following code:
Private Function ReadHtml(ByVal text As String) As Paragraph
Dim par = NewParagraph()
Try
Dim htmlText = Server.HtmlDecode(text)
If Not htmlText.StartsWith("<") Then
htmlText = "<span>" & htmlText & "</span>"
End If
Using reader As New IO.StringReader(htmlText)
Dim mh As New MyHandler()
XMLWorkerHelper.GetInstance().ParseXHtml(mh, reader)
'use mh.elements
For Each element In mh.Elements
Dim list = TryCast(element, List)
If list IsNot Nothing Then
element = Clone(list)
End If
par.Add(element)
Next
setFont(par, m_rowFont)
End Using
Catch ex As Exception
Throw New Exception("Exception in ReadHtml using: '" & text & "'")
End Try
Return par
End Function
When this function returns, I take the paragraph and insert it into the PDF. The problem I am having is that while I can set the font in an outer div, and the resulting PDF will render that correctly, if I include an HTML table inside of the div where I've set the font, everything inside of the table renders using the Page's default font.
How do I control the font of the table content?

Your Html in font-size and font-family remove.
public string ConvertPdfHtml(string html)
{
html = CleanStyleAttribute(html, "font-family");
html = CleanStyleAttribute(html, "font-size");
....
return html;
}
private string CleanStyleAttribute(string html, string styleAttributeName)
{
return Regex.Replace(html, styleAttributeName + "(?>:(.*?);)","");
}

Related

How can I add text to a document footer using OpenXML?

I have a document template that I want to append some text to the footer. I've seen ways of deleting the footer to replace it, and ways to replace text in the footer, but I want to keep the footer as is from the template and just add to it. I have code to add text to the main doc., but unfortunately, main doc. parts are not setup the same way as footer parts. This is easily accomplished in Interop by a range.InsertAfter(text), but end users need this to work sans Word.
FooterPart footer = _doc.MainDocumentPart.FooterParts.ElementAtOrDefault(0);
string rid = _doc.MainDocumentPart.GetIdOfPart(footer);
footer = _doc.MainDocumentPart.AddNewPart<FooterPart>(rid);
Paragraph para = footer.AddPart(new Paragraph(), rid);
Run run = para.AppendChild(new Run());
// get the last footer of the document
FooterPart footerPart = _doc.MainDocumentPart.FooterParts.LastOrDefault();
// create your paragraph. i created simple, but you will need to add style properties to the run or text class
Paragraph pr = new Paragraph(new Run(new Text("hello")));
// Insert the Paragraph to the end of the footer in footerPart.Footer
footerPart.Footer.AppendChild(pr);
Other way as you said would be putting a text to replace like "txttoreplace" and then you will find it and replace
IEnumerable<FooterPart> footerPartsList = Documento.MainDocumentPart.FooterParts.ToList();
foreach (FooterPart hp in footerPartsList)
foreach (Text text in hp.RootElement.Descendants<Text>())
{
if (text.Text.Contains("txttoreplace"))
{
text.Text = text.Text.Replace("txttoreplace", "new text");
}
}
And another way and the hardest would be, you inser the whole footer, with open xml productivity tools you get the c# code of the footer.xml, and then you delete the footer of the document and you insert.

How can I get text value of TMPro Text without markup tags in Unity?

I am trying to get text value in TMPro Text component without markup tags but haven't found any solutions.
Say, <b><color=red>Hello </color><b> world is the value in TMPro Text, and I just want Hello world in c# script.
Bear in mind that tag <b> and color will change, so I would love to remove tags dynamically, meaning I would like not to replacing each tag by text.replace("<b>", "") kind of things.
Does anyone know how to do it?
I dont know about the option of using HTML on tmp but you can attach the text to your script by create a new variable like that:
[SerializeField] TMP_Text textVar;
then you can drag you tmp game object to the component that include this script
and the you can change the text like that:
textVar.text = "what ever";
or get text like that:
string textString = textVar.text;
for the color you can use
Color color = textVar.color;
You can use TMP_Text.GetParsedText () to get the text after it has been parsed and rich text tags removed.
Alternatively you can also use regular expressions to search a string for rich text tags, and remove them while preserving the rest of the string.
using System.Text.RegularExpressions;
public static string GetString (string str)
{
Regex rich = new Regex (#"<[^>]*>");
if (rich.IsMatch (str))
{
str = rich.Replace (str, string.Empty);
}
return str;
}

how to apply html to SuggestList popup

How can I apply html to SuggestList popup in Gwt?
I want to apply html table in suggest list popup.
eg:
private SuggestOracle getSuggest() {
oracle = new MultiWordSuggestOracle();
oracle.add("<table border=1><tr><td>hussain</td></tr><td>hussain1</td></table>");
oracle.add("<table border=1><tr><td>taher</td></tr><td>taher1</td></table>");
oracle.add("<table border=1><tr><td>hussain22</td></tr><td>hussain2</td></table>");
return oracle;
}
The popup should show table with 2 column but it is taking html as text
Thanks
Husein
Override MultiWordSuggestOracle#isDisplayStringHTML().
Should SuggestOracle.Suggestion display strings be treated as HTML? If true, this all suggestions' display strings will be interpreted as HTML, otherwise as text.
MultiWordSuggestOracle oracle = new MultiWordSuggestOracle(){
#Override
public boolean isDisplayStringHTML(){
return true;
}
};
Note: Each suggestion has a display string and a replacement string.
For more info have a look at SuggestOracle.Suggestion
--EDIT--
For more info have a look at MultiWordSuggestOracle and HTML display
complete sample code:
MultiWordSuggestOracle oracle = new MultiWordSuggestOracle() {
#Override
public boolean isDisplayStringHTML() {
return true;
}
};
Collection<Suggestion> suggestionList = new ArrayList<Suggestion>();
suggestionList.add(new MultiWordSuggestOracle.MultiWordSuggestion("hussain",
"<table border='1'><tr><td>hussain</td></tr></table>"));
suggestionList.add(new MultiWordSuggestOracle.MultiWordSuggestion("taher1",
"<table border='1'><tr><td>taher1</td></tr></table>"));
suggestionList.add(new MultiWordSuggestOracle.MultiWordSuggestion("hussain2",
"<table border='1'><tr><td>hussain2</td></tr></table>"));
oracle.setDefaultSuggestions(suggestionList);

Using iText to fill text field background

I am trying to Use iText to fill the color of a text field. I have tried setfieldproperty and it does not work with bgcolor or fill color attribute. What I am looking for is the property of the text field to set as it will be overlayed existing text or image
I have tried the couple of cases at the end..
' 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)**
I just want to change the color of one text field background
When you manually edit the Text Field within the Document. The appearance tab of the properties. It has the property for Fill color and border color
I am able to do the border color..
I cannot seem to do the fill color property within code..
The background color is stored in the display widget of a form field under the MK key (PDF Spec 12.5.6.19)
Below is sample code that sets the background color in two different ways. The first block creates a brand new PDF and adds a form field directly to it. When done this way you can just set the MKBackgroundColor property on the FormField and you're all set. The second block edits the first block's PDF, gets the named field, creates a new dictionary, adds the color to it and assigns it to the field's widget (destroying any existing MK entries in the process).
The first block of code is the much easier route. See the comments in the code for more information.
''//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

Using PDF itextSharp it is possible to put an image on top of text while creating the pdf document

I attempted several ways to do this, but still cannot get it.
It appears iTextSharp requires a 2 pass situation so that an image appears on top of the text.
So I am attempting to do this using memory streams, but I keep getting errors.
Public Function createDoc(ByRef reqResponse As HttpResponse) As Boolean
Dim m As System.IO.MemoryStream = New System.IO.MemoryStream()
Dim document As Document = New Document()
Dim writer As PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, m)
document.Open()
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Add(New Paragraph(DateTime.Now.ToString()))
document.Close()
writer.Flush()
writer.Flush()
'yes; I get the pdf if this is the last statement
'reqResponse.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length)
'this statment does not work it says the stream is closed
'm.Position = 0
Dim Reader As PdfReader = New PdfReader(m)
'Dim rm As MemoryStream = New MemoryStream(m.GetBuffer(), 0, m.GetBuffer().Length)
Dim PdfStamper As PdfStamper = New PdfStamper(Reader, reqResponse.OutputStream)
Dim cb As iTextSharp.text.pdf.PdfContentByte = Nothing
cb = PdfStamper.GetOverContent(1)
Dim locMyImage As System.Drawing.Image = System.Drawing.Image.FromStream(zproProduceWhiteImageToCovertBarCodeNumbers())
Dim BImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(locMyImage, iTextSharp.text.BaseColor.CYAN)
Dim overContent As PdfContentByte = PdfStamper.GetOverContent(1)
BImage.SetAbsolutePosition(5, 5)
overContent.AddImage(BImage)
PdfStamper.FormFlattening = True
PdfStamper.Close()
'rm.Flush()
'rm.Close()
'Dim data As Byte() = rm.ToArray()
'reqResponse.Clear()
'Dim finalMs As MemoryStream = New MemoryStream(data)
'reqResponse.ContentType = "application/pdf"
'reqResponse.AddHeader("content-disposition", "attachment;filename=labtest.pdf")
'reqResponse.Buffer = True
'finalMs.WriteTo(reqResponse.OutputStream)
'reqResponse.End()
'Dim data As Byte() = rm.ToArray()
'reqResponse.OutputStream.Write(data, 0, data.Length)
''Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
''Response.OutputStream.Flush();
''Response.OutputStream.Close();
''Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest()
Return True
End Function
reference:
Put text on top of an image?
seach engine reference:
whiteout text on a pdf document by using a image which is the same color as the background pdf
image overlap with itextpdf
itextsharp image on top of the text whiteout
itextsharp place picture on top of text
itextpdf image on top
thanks,
Doug Lubey of Louisiana
You can do this pretty easily. The Document object is a helper object that abstracts away many of the internals of the PDF model and for the most part assumes that you want to flow content and that text would go above images. If you want to get around this you can talk directly the PdfWriter object instead. It has two properties, DirectContent and DirectContentUnder that both have methods named AddImage() that you can use to set an absolute position on an image. DirectContent is above existing content and DirectContentUnder is below it. See the code for an example:
You appear to be doing this on the web so you'll need to adapt this to whatever stream you are using but that should be pretty easy.
One note, NEVER call GetBuffer() on a MemoryStream, ALWAYS use ToArray(). The former method includes uninitialized bytes that will give you potentially corrupt PDFs.
''//File that we are creating
Dim OutputFile As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf")
''//Image to place
Dim SampleImage As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SampleImage.jpg")
''//Standard PDF creation setup
Using FS As New FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)
Using Doc As New Document(PageSize.LETTER)
Using writer = PdfWriter.GetInstance(Doc, FS)
''//Open the document for writing
Doc.Open()
''//Add a simple paragraph
Doc.Add(New Paragraph("Hello world"))
''//Create an image object
Dim Img = iTextSharp.text.Image.GetInstance(SampleImage)
''//Give it an absolute position in the top left corner of the document (remembering that 0,0 is bottom left, not top left)
Img.SetAbsolutePosition(0, Doc.PageSize.Height - Img.Height)
''//Add it directly to the raw pdfwriter instead of the document helper. DirectContent is above and DirectContentUnder is below
writer.DirectContent.AddImage(Img)
''//Close the document
Doc.Close()
End Using
End Using
End Using