iText7 SetJustification(2) works partially - c#

I have a code which takes a PDF template, inserts some input values into the template and creates an output PDF file.
One of the fields in the PDF file is a free text which can include a value with Hebrew/English/Numbers or signs characters.
I'm using the following code to make the text readable in Hebrew with RTL display:
iText.Kernel.Pdf.PdfReader reader = new iText.Kernel.Pdf.PdfReader(pdfTemplatePath); //src);
iText.Kernel.Pdf.PdfWriter writer = new iText.Kernel.Pdf.PdfWriter(pdfOutPutFile); //dest);
iText.Kernel.Pdf.PdfDocument pdf = new iText.Kernel.Pdf.PdfDocument(reader, writer);
iText.Forms.PdfAcroForm form = iText.Forms.PdfAcroForm.GetAcroForm(pdf, true);
IDictionary<String, iText.Forms.Fields.PdfFormField> fields = form.GetFormFields();
// iText.Kernel.Font.PdfFont = iText.Kernel.Font.PdfFontFactory.CreateFont(iText.IO.Font.FontProgram
FontProgramFactory.RegisterFont(#"C:\Windows\Fonts\ARIALUNI.TTF", "arialUnicode");
iText.Kernel.Font.PdfFont myFont = PdfFontFactory.CreateRegisteredFont("arialUnicode", iText.IO.Font.PdfEncodings.IDENTITY_H, true);
pdf.GetFirstPage().GetResources().AddFont(pdf, myFont);
// Set Field value by Fields mapping
foreach (string fieldName in formFieldMap.Keys)
{
fields[fieldName].SetValue(formFieldMap[fieldName].ToString());
fields[fieldName].SetFont(myFont);
// displaying the text: 0 Left-justified 1 Centered 2 Right-justified
**fields[fieldName].SetJustification(2);**
}
My problem is that the text is not aligned to right.
Field with text-align left:
What more can I do to set the text-align on the right?

Related

Itext7 not showing arabic text

I am trying to create a Pdf document using IText7. Despite the table looks as expected, just found a big problem, this does not show Arabic letters.
I've tried adding new fonts and changing the encoding.
I'm displaying Arabic letters in the wrong direction and they are separated, changing the base direction from right to left didn't help.
This is the part of the code:
string font = "naskh.ttf";
PdfFontFactory.Register(font);
FontProgram fontProgram = FontProgramFactory.CreateFont(font, true);
PdfFont f = PdfFontFactory.CreateFont(font,true);
Cell cell = new Cell(1, 3)
.Add(new Paragraph(" English عربي "))
.SetFont(f).SetFontScript(UnicodeScript.ARABIC)
.SetFontSize(33).SetBaseDirection(BaseDirection.RIGHT_TO_LEFT)
.SetFontColor(DeviceGray.WHITE)
.SetBackgroundColor(new DeviceRgb(80, 140, 80))
.SetTextAlignment(TextAlignment.CENTER);
The result is like this:
I've tried everything I could find online, lots of them are java or older version, I tried to change them to work on c# Itext7 but still no result
the closest I cot was with PdfFont f = PdfFontFactory.CreateFont(alaw, "Identity-H", true);
where I got 3 letters in the wrong order
I even tried to use \u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628 (copied from an answer as string, but still not shown.
I can't use paid add-ons
Any solution to be able to write Arabic?
add language Processor:
LanguageProcessor languageProcessor = new ArabicLigaturizer();
and modify cell or PdfDocument like that:
com.itextpdf.kernel.pdf.PdfDocument tempPdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(pdfFile.getPath()), TempWriter);
com.itextpdf.layout.Document TempDoc = new com.itextpdf.layout.Document(tempPdfDoc);
com.itextpdf.layout.element.Paragraph paragraph0 = new com.itextpdf.layout.element.Paragraph(languageProcessor.process("الاستماره الالكترونية--الاستماره الالكترونية--الاستماره الالكترونية--الاستماره الالكترونية"))
.setFont(f).setBaseDirection(BaseDirection.RIGHT_TO_LEFT)
.setFontSize(15);
the final will be something like :
String font = "your Arabic font";
PdfFontFactory.register(font);
FontProgram fontProgram = FontProgramFactory.createFont(font, true);
PdfFont f = PdfFontFactory.createFont(fontProgram, PdfEncodings.IDENTITY_H);
LanguageProcessor languageProcessor = new ArabicLigaturizer();
com.itextpdf.kernel.pdf.PdfDocument tempPdfDoc = new
com.itextpdf.kernel.pdf.PdfDocument(new PdfReader(pdfFile.getPath()), TempWriter);
com.itextpdf.layout.Document TempDoc = new
com.itextpdf.layout.Document(tempPdfDoc);
com.itextpdf.layout.element.Paragraph paragraph0 = new
com.itextpdf.layout.element.Paragraph(languageProcessor.process("الاستماره الالكترونية--الاستماره الالكترونية--الاستماره الالكترونية--الاستماره الالكترونية"))
.setFont(f).setBaseDirection(BaseDirection.RIGHT_TO_LEFT)
.setFontSize(15);
//and look how i useded setBaseDirection & and don't use TextAlignment ,it will work without it

Search Text and highlight it

My code is in C#
I am using Aspose to search text and highlight it in pdf.
It is working but the time taken is very huge.
Example : My document has 25 pages and it has 25 instance of search text , 1 search text in each page.
It take 2 minutes which is unacceptable.
I have 3 questions:
Is it a way to reduce this time taken ?
Currently this approach is for pdf, in my case i have all types of doc (xls, pdf, ppt, doc)? Is there any way where this search and highlighting can be performed in all docs ?
Is there some better way of doing it other than aspose ?
// open document
Document document = new Document(#"C:\TestArea\Destination\SUP000011\ATM-1B4L2KQ0ZE0-0001\OpenAML.pdf");
//create TextAbsorber object to find all instances of the input search phrase
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Martin");
//accept the absorber for all the pages
for (int i = 1; i <= document.Pages.Count; i++)
{
document.Pages[i].Accept(textFragmentAbsorber);
//get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
//loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
//update text and other properties
// textFragment.TextState.Invisible = false;
//textFragment.Text = "TEXT";
textFragment.TextState.Font = FontRepository.FindFont("Verdana");
textFragment.TextState.FontSize = 9;
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue);
textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Yellow);
//textFragment.TextState.Underline = true;
}
}
// Save resulting PDF document.
document.Save(#"C:\TestArea\Destination\SUP000011\ATM-1B4L2KQ0ZE0-0001\Highlightdoc.pdf");

How to find and replace the text in the footer of the word document using open XML SDK?

I tried the below code. It works if it is a normal text and left indent is on. If I have the text with the square brackets, it corrupts the docx, and if I have the text to be center aligned in footer, replacing doesn't work. Please help me. Here is my code.
using (var file = WordprocessingDocument.Open(targetFileName, true))
{
string content = null;
using (StreamReader reader = new StreamReader(
file.MainDocumentPart.FooterParts.First().GetStream()))
{
content = reader.ReadToEnd();
}
Regex expression = new Regex("[name]");
content = expression.Replace(content,"replacement word");
using (StreamWriter writer = new StreamWriter(
file.MainDocumentPart.FooterParts.First().GetStream(FileMode.Create)))
{
writer.Write(content);
}
file.MainDocumentPart.Document.Save();
}
I want to replace multiple words in the footer like [name] | [email] | [telephone]
Document will be corrupted when the text to be replaced has [] in it.
Thanks in advance
What is happening in the above code is that every instance of "n", "a", "m", "e" is being replaced with the entire string "replacement word". The xml headers in the .docx file contain those characters, which are being overwritten and corrupted when the Regex runs the Replace function.
This can be fixed by escaping the [] characters as follows:
Regex expression = new Regex("\\[name\\]");

How to make Some text bold in a paragraph while generating from novacode docx library in c#

I want to make some text bold like that..
• Basic – There are no Cybersecurity
One way of doing this is to insert the bolded text separately into the same paragraph.
// Create the proper formats first
Formatting bold = new Formatting();
bold.Bold = true;
Formatting notBold = new Formatting();
// Create the file
DocX doc = DocX.Create("test.docx");
// Insert the text you want with the proper formatting for each section
Paragraph para = doc.InsertParagraph();
para.InsertText("not bold text ", false, notBold);
para.InsertText("bold text ", false, bold);
para.InsertText("not bold text", false, notBold);
doc.Save();
This will output:
not bold text bold text not bold text

iText C# exact text displaying

I am trying to insert the exact text with the spaces at the beginning of line, however iText eats all the spaces before the first visible symbol (tabulation does't work as well).
I am using iText 7 Community edition.
C# code:
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
//Initialize PDF writer
PdfWriter writer = new PdfWriter(DEST);
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document doc = new Document(pdf);
doc.Add(new Paragraph("Test\n\tTest\n Test\n Test 1 2 3"));
doc.Close();
That code display the text in the output .pdf document as
Test
Test
Test
Test 1 2 3
Without any tabs and spaces before the fist visible symbol of each line.
How can I change code to get
Test
Test
Test
Test 1 2 3
in the output document?
In your code example, (embedded) tabs wouldn't work in iTextSharp 5.xx.xx either, although spaces are respected. What's a little surprising, as you've proved, is that iText7 strips spaces following a newline. Not sure if you need support for either or both, so will give an example that handles each case separately:
First, preserving tabs:
Paragraph p = new Paragraph("Line 0\n")
.AddTabStops(new TabStop(8f))
// change to your needs ^^
.Add(new Tab())
.Add("Line 1");
doc.Add(p);
Second, preserving spaces immediately following a newline:
string[] lines = "0\n1\n 2\n 3\n".Split(
new string[] { "\n" },
StringSplitOptions.RemoveEmptyEntries
);
p = new Paragraph().AddStyle(
new Style().SetFont(PdfFontFactory.CreateFont(FontConstants.COURIER))
);
foreach (var l in lines)
{
if (Regex.IsMatch(l, #"^\s+"))
{
p.Add(" ") // all spaces stripped, whether one or more characters
.Add(l) // now leading whitespace preserved
.Add("\n");
}
else
{
p.Add(l).Add("\n");
}
}
doc.Add(p);
This is the first time I've looked at/written any iText7, so there's likely a different/better way, and I don't consider it anything but a workaround. Oddly, if you add any number of space characters following a newline and then immediately add a string that's also preceded with space characters, the first call strips space, but the second preserves them.
As a side note, one thing I noticed right away and really like about the new API is you can use method chaining all over the place. :)
Here's the result:
You should use Chunks to add text to a paragraph.
Then you should set tab settings and use specific Chunk.TABBING
p = new Paragraph();
p.setTabSettings(new TabSettings(56f));
p.add(Chunk.TABBING);
p.add(new Chunk("Hello World with tab."));
This sample is located at iText examples
Just try this.
Font bodyFont = FontFactory.GetFont("Times New Roman", 10, Font.NORMAL);
file.Directory.Create();
//Initialize PDF writer
PdfWriter writer = new PdfWriter(DEST);
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document doc = new Document(pdf);
doc.Add(new Paragraph("Test", bodyFont));
doc.Add(new Paragraph(" Test", bodyFont));
doc.Add(new Paragraph(" Test", bodyFont));
doc.Add(new Paragraph(" Test 1 2 2", bodyFont));
doc.Close();

Categories

Resources