Ich arbeite mit ITEXT 9.3.0 für .NET und muss ein PDF-Formfeld (pdftextFieldfield) mit arabischem Text füllen und es dann verflachten, damit der Text dauerhaft wird. Mein Code: < /p>
using var inputStream = new MemoryStream(templateBytes);
using var outputStream = new MemoryStream();
using var pdfReader = new iText.Kernel.Pdf.PdfReader(inputStream);
using var pdfWriter = new PdfWriter(outputStream);
using var pdfDoc = new iText.Kernel.Pdf.PdfDocument(pdfReader, pdfWriter);
var form = PdfAcroForm.GetAcroForm(pdfDoc, true);
using var layoutDoc = new Document(pdfDoc);
var field = form.GetField("arabicField");
try
{
if (IsArabicText(value.Value))
{
var fontFile = Path.Combine(_fontsDir, "Almarai-Regular.ttf");
//PdfFont pdfFont = PdfFontFactory.CreateFont(fontFile, PdfEncodings.IDENTITY_H, EmbeddingStrategy.FORCE_EMBEDDED);
// Set Arabic value
field.SetValue(value.Value);
// Align right for RTL
field.SetJustification(2); // right aligned
// Regenerate field appearance
}
else
{
field.SetValue(value.Value);
}
field.RegenerateField();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to set text for field {FieldId}", value.Id);
}
form.FlattenFields();
layoutDoc.Close();
< /code>
[b] Was ich ausprobiert habe < /strong>
Einbettung einer arabischen Schrift (z. B. Almarai, Noto Naskh Arabic). Form.SetNeedAppearances (True). FACHTEMED FORMULE. Datei < /p>
public async Task CreateTemplateAsync(IFormFile file, List fields)
{
try
{
using var inputStream = new MemoryStream();
await file.CopyToAsync(inputStream);
inputStream.Position = 0;
byte[] finalPdfBytes;
using (var pdfReader = new iText.Kernel.Pdf.PdfReader(inputStream))
using (var outputStream = new MemoryStream())
using (var pdfWriter = new PdfWriter(outputStream))
using (var pdfDoc = new iText.Kernel.Pdf.PdfDocument(pdfReader, pdfWriter))
{
// Add fields
foreach (var field in fields)
{
AddFieldToDocument(pdfDoc, field);
}
pdfDoc.Close();
finalPdfBytes = outputStream.ToArray();
}
return Convert.ToBase64String(finalPdfBytes);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating PDF template");
throw;
}
}
private void AddFieldToDocument(iText.Kernel.Pdf.PdfDocument pdfDoc, TemplateField field)
{
try
{
var form = PdfFormCreator.GetAcroForm(pdfDoc, true);
if (field.Page < 0 || field.Page >= pdfDoc.GetNumberOfPages())
{
_logger.LogWarning("Invalid page index {Page} for field {FieldId}", field.Page, field.Id);
return;
}
var page = pdfDoc.GetPage(field.Page + 1);
var pageHeight = page.GetPageSize().GetHeight();
var text = field.DefaultValue ?? string.Empty;
float x = (float)field.Position.X;
float y = pageHeight - (float)field.Position.Y - (float)field.Size.Height;
// Safely resolve font size (default 12)
float fontSize = field?.Formatting?.FontSize ?? 12;
// Calculate dynamic width
float calculatedWidth = fontSize * 0.9f * text.Length;
float width = Math.Max(calculatedWidth, 100f);
// Use field height
float height = (float)field?.Size?.Height!;
// Special handling for Arabic text box sizing (keep only for box size, not text)
if (!string.IsNullOrEmpty(field.DefaultValue) && Regex.IsMatch(field.DefaultValue, @"\p{IsArabic}"))
{
y -= (field.Formatting?.FontSize ?? 12) * 0.2f;
height *= 1.85f;
}
var rect = new Rectangle(x, y, width, height);
PdfFormField createdField = null;
switch (field.Type)
{
case FieldType.Text:
case FieldType.FullName:
case FieldType.Email:
case FieldType.JobTitle:
case FieldType.Company:
case FieldType.Mobile:
case FieldType.SignDate:
case FieldType.HijriDate:
{
var textField = new TextFormFieldBuilder(pdfDoc, field.Id)
.SetWidgetRectangle(rect)
.CreateText();
ApplyFormatting(textField, field);
createdField = textField;
break;
}
default:
{
var fallback = new TextFormFieldBuilder(pdfDoc, field.Id)
.SetWidgetRectangle(rect)
.CreateText();
ApplyFormatting(fallback, field);
createdField = fallback;
break;
}
}
if (createdField != null)
{
if (!string.IsNullOrEmpty(field.Label))
createdField.SetAlternativeName(field.Label);
if (field.Required)
createdField.SetRequired(true);
form.AddField(createdField, page);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error adding field {FieldId} to document", field.Id);
}
}
private void ApplyFormatting(PdfFormField field, TemplateField source)
{
try
{
// -------- FONT RESOLUTION --------
if (!string.IsNullOrEmpty(source.Formatting?.FontFamily))
{
var font = ResolveFont(source.Formatting);
font.SetSubset(false);
field.SetFont(font);
}
else
{
field.SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA));
}
// -------- FONT SIZE --------
if (source.Formatting?.FontSize > 0)
{
field.SetFontSize(source.Formatting.FontSize);
}
// -------- COLOR --------
if (!string.IsNullOrEmpty(source.Formatting?.Color))
{
field.SetColor(HexToRgb(source.Formatting.Color));
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error applying formatting for field {FieldId}", source.Id);
}
}
< /code>
using System.IO;
using iText.Forms;
using iText.Forms.Fields;
using iText.Kernel.Pdf;
using iText.Kernel.Font;
public class ArabicFieldTest
{
public byte[] FillArabic(byte[] templateBytes, string fieldName, string arabicValue, string fontsDir)
{
using var inputStream = new MemoryStream(templateBytes);
using var outputStream = new MemoryStream();
using var pdfReader = new PdfReader(inputStream);
using var pdfWriter = new PdfWriter(outputStream);
using var pdfDoc = new PdfDocument(pdfReader, pdfWriter);
var form = PdfAcroForm.GetAcroForm(pdfDoc, true);
form.SetNeedAppearances(false);
form.SetGenerateAppearance(true);
string fontPath = Path.Combine(fontsDir, "NotoNaskhArabic-Regular.ttf");
PdfFont arabicFont = PdfFontFactory.CreateFont(fontPath, PdfEncodings.IDENTITY_H);
PdfFormField field = form.GetField(fieldName);
field.SetFont(arabicFont);
field.SetValue(arabicValue);
pdfDoc.Close();
return outputStream.ToArray();
}
}
< /code>
I don't know how to add/attach/upload a pdf file here, but any pdf file will show same result.
EDIT-2[/b]
I tried the code in the answer and its weird that i get completely different result.
I am on version itext 9.3.0 and project is in dotnet 9.0
#region testregin
// Assuming `document` is your byte[]
var output = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample PDF.pdf");
// Save to file
//await System.IO.File.WriteAllBytesAsync(filePath, document);
//String output = DESTINATION_FOLDER + "soTest1.pdf";
String text = " هل تتكلم الانجليزية؟ ";
//string text = fields.Where(x => IsArabicText(x.DefaultValue)).FirstOrDefault().DefaultValue;
iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(new PdfWriter(output));
BaseDirection direction = BaseDirection.RIGHT_TO_LEFT;
Document document = new Document(pdfDocument);
document.SetBaseDirection(direction);
string FONTS_FOLDER = System.IO.Path.Combine(_fontsDir);
PdfFont arabic = PdfFontFactory.CreateFont(FONTS_FOLDER + "\\NotoNaskhArabic-Regular.ttf",
PdfEncodings.IDENTITY_H);
//PdfFont arabic = PdfFontFactory.CreateFont(FONTS_FOLDER + "NotoNaskhArabic-Regular.ttf",
// PdfEncodings.IDENTITY_H);
Paragraph p = new Paragraph().SetBorder(new SolidBorder(ColorConstants.RED, 1));
p.Add(text).SetFont(arabic);
p.SetTextAlignment(TextAlignment.RIGHT);
document.Add(p);
document.Add(new Paragraph("----------------------"));
InputField field3 = new InputField("field");
field3.SetWidth(520f);
field3.SetBorder(new SolidBorder(ColorConstants.BLUE, 1));
field3.SetInteractive(true);
field3.SetTextAlignment(TextAlignment.RIGHT);
document.Add(field3);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDocument, true);
PdfFormField field1 = form.GetField("field");
field1.SetFont(arabic);
field1.SetValue(text);
form.FlattenFields();
pdfDocument.Close();
#endregion
```
[enter image description here][1]
[1]: https://i.sstatic.net/TNhvnHJj.png
Ich arbeite mit ITEXT 9.3.0 für .NET und muss ein PDF-Formfeld (pdftextFieldfield) mit arabischem Text füllen und es dann verflachten, damit der Text dauerhaft wird. Mein Code: < /p> [code]using var inputStream = new MemoryStream(templateBytes); using var outputStream = new MemoryStream();
using var pdfReader = new iText.Kernel.Pdf.PdfReader(inputStream); using var pdfWriter = new PdfWriter(outputStream); using var pdfDoc = new iText.Kernel.Pdf.PdfDocument(pdfReader, pdfWriter);
var form = PdfAcroForm.GetAcroForm(pdfDoc, true); using var layoutDoc = new Document(pdfDoc);
var field = form.GetField("arabicField");
try { if (IsArabicText(value.Value)) { var fontFile = Path.Combine(_fontsDir, "Almarai-Regular.ttf"); //PdfFont pdfFont = PdfFontFactory.CreateFont(fontFile, PdfEncodings.IDENTITY_H, EmbeddingStrategy.FORCE_EMBEDDED);
// Set Arabic value field.SetValue(value.Value);
// Align right for RTL field.SetJustification(2); // right aligned
// Regenerate field appearance } else { field.SetValue(value.Value); }
field.RegenerateField(); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to set text for field {FieldId}", value.Id); }
form.FlattenFields(); layoutDoc.Close(); < /code> [b] Was ich ausprobiert habe < /strong> Einbettung einer arabischen Schrift (z. B. Almarai, Noto Naskh Arabic). Form.SetNeedAppearances (True). FACHTEMED FORMULE. Datei < /p> public async Task CreateTemplateAsync(IFormFile file, List fields) { try { using var inputStream = new MemoryStream(); await file.CopyToAsync(inputStream); inputStream.Position = 0;
byte[] finalPdfBytes;
using (var pdfReader = new iText.Kernel.Pdf.PdfReader(inputStream)) using (var outputStream = new MemoryStream()) using (var pdfWriter = new PdfWriter(outputStream)) using (var pdfDoc = new iText.Kernel.Pdf.PdfDocument(pdfReader, pdfWriter)) { // Add fields foreach (var field in fields) { AddFieldToDocument(pdfDoc, field); }
return Convert.ToBase64String(finalPdfBytes); } catch (Exception ex) { _logger.LogError(ex, "Error creating PDF template"); throw; } } private void AddFieldToDocument(iText.Kernel.Pdf.PdfDocument pdfDoc, TemplateField field) { try { var form = PdfFormCreator.GetAcroForm(pdfDoc, true);
if (field.Page < 0 || field.Page >= pdfDoc.GetNumberOfPages()) { _logger.LogWarning("Invalid page index {Page} for field {FieldId}", field.Page, field.Id); return; }
var page = pdfDoc.GetPage(field.Page + 1); var pageHeight = page.GetPageSize().GetHeight();
var text = field.DefaultValue ?? string.Empty; float x = (float)field.Position.X; float y = pageHeight - (float)field.Position.Y - (float)field.Size.Height;
// Use field height float height = (float)field?.Size?.Height!;
// Special handling for Arabic text box sizing (keep only for box size, not text) if (!string.IsNullOrEmpty(field.DefaultValue) && Regex.IsMatch(field.DefaultValue, @"\p{IsArabic}")) { y -= (field.Formatting?.FontSize ?? 12) * 0.2f; height *= 1.85f; }
var rect = new Rectangle(x, y, width, height); PdfFormField createdField = null;
switch (field.Type) { case FieldType.Text: case FieldType.FullName: case FieldType.Email: case FieldType.JobTitle: case FieldType.Company: case FieldType.Mobile: case FieldType.SignDate: case FieldType.HijriDate: { var textField = new TextFormFieldBuilder(pdfDoc, field.Id) .SetWidgetRectangle(rect) .CreateText();
ApplyFormatting(textField, field); createdField = textField; break; } default: { var fallback = new TextFormFieldBuilder(pdfDoc, field.Id) .SetWidgetRectangle(rect) .CreateText();
if (createdField != null) { if (!string.IsNullOrEmpty(field.Label)) createdField.SetAlternativeName(field.Label);
if (field.Required) createdField.SetRequired(true);
form.AddField(createdField, page); } } catch (Exception ex) { _logger.LogError(ex, "Error adding field {FieldId} to document", field.Id); } }
private void ApplyFormatting(PdfFormField field, TemplateField source) { try { // -------- FONT RESOLUTION -------- if (!string.IsNullOrEmpty(source.Formatting?.FontFamily)) { var font = ResolveFont(source.Formatting); font.SetSubset(false); field.SetFont(font); } else { field.SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA)); }
// -------- FONT SIZE -------- if (source.Formatting?.FontSize > 0) { field.SetFontSize(source.Formatting.FontSize); }
// -------- COLOR -------- if (!string.IsNullOrEmpty(source.Formatting?.Color)) { field.SetColor(HexToRgb(source.Formatting.Color)); } } catch (Exception ex) { _logger.LogWarning(ex, "Error applying formatting for field {FieldId}", source.Id); } }
< /code> using System.IO; using iText.Forms; using iText.Forms.Fields; using iText.Kernel.Pdf; using iText.Kernel.Font;
public class ArabicFieldTest { public byte[] FillArabic(byte[] templateBytes, string fieldName, string arabicValue, string fontsDir) { using var inputStream = new MemoryStream(templateBytes); using var outputStream = new MemoryStream();
using var pdfReader = new PdfReader(inputStream); using var pdfWriter = new PdfWriter(outputStream); using var pdfDoc = new PdfDocument(pdfReader, pdfWriter); var form = PdfAcroForm.GetAcroForm(pdfDoc, true);
PdfFormField field = form.GetField(fieldName); field.SetFont(arabicFont); field.SetValue(arabicValue);
pdfDoc.Close(); return outputStream.ToArray(); } } < /code> I don't know how to add/attach/upload a pdf file here, but any pdf file will show same result. EDIT-2[/b] I tried the code in the answer and its weird that i get completely different result. I am on version itext 9.3.0 and project is in dotnet 9.0 #region testregin
// Assuming `document` is your byte[] var output = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample PDF.pdf");
// Save to file //await System.IO.File.WriteAllBytesAsync(filePath, document);
//String output = DESTINATION_FOLDER + "soTest1.pdf"; String text = " هل تتكلم الانجليزية؟ "; //string text = fields.Where(x => IsArabicText(x.DefaultValue)).FirstOrDefault().DefaultValue; iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(new PdfWriter(output));
BaseDirection direction = BaseDirection.RIGHT_TO_LEFT; Document document = new Document(pdfDocument); document.SetBaseDirection(direction);
Paragraph p = new Paragraph().SetBorder(new SolidBorder(ColorConstants.RED, 1)); p.Add(text).SetFont(arabic); p.SetTextAlignment(TextAlignment.RIGHT); document.Add(p);
Ich habe Probleme, den arabischen Text in PDF -Dateien korrekt zu machen, die mit der Itext 7 -Bibliothek mit der Programmiersprache .NET generiert wurden. Arabische Buchstaben erscheinen voneinander...
Ich habe eine Anwendung in Java, Spring Boot und Logback. In der Logback-Datei ist, wie wir unten sehen können, ein Teil von OpenTelemetry konfiguriert. Ich erhalte meine Protokolle im...
Wie füge ich einen Serienpunkt in einem pyside6 qchart hinzu?
Ich bin mir nicht sicher, ob es ein Fehler ist, aber ich kann kein funktionierendes Beispiel finden. import sys
Wie füge ich einen Serienpunkt in einem pyside6 qchart hinzu?
Ich bin mir nicht sicher, ob es ein Fehler ist, aber ich kann kein funktionierendes Beispiel finden. import sys
Ich erstelle ein PDF -Dokument mit mehreren Seiten mit iText. Ich füge einen einzigartigen Text auf einer der Seiten in der Mitte dieses Dokuments hinzu, mache es aber unsichtbar als as-