Search code examples
.net-core.net-6.0itext7

With iText7,How to specifies the width and color of strokes for text?


I's there any solution for iText 7 to specify the stroke width and stroke color for text?

The code I have tried so far:

using var doc = new PdfDocument(new PdfWriter("a4.pdf"));
var pageSize = PageSize.A4;
var page = doc.AddNewPage(pageSize);
PdfCanvas pdfCanvas = new PdfCanvas(page);
var canvas = new Canvas(pdfCanvas, pageSize);
Paragraph p = new Paragraph("This is a Paragraph");
p.SetFontSize(20f);
p.SetLineThrough();//can through line
//how to add a stroke to text?
canvas.ShowTextAligned(p, pageSize.GetLeft()+100, pageSize.GetTop() - 100, 1, iText.Layout.Properties.TextAlignment.LEFT, iText.Layout.Properties.VerticalAlignment.TOP, 0f);
doc.Close();
using (System.Diagnostics.Process process = new System.Diagnostics.Process())
{
    process.StartInfo = new System.Diagnostics.ProcessStartInfo()
    {
        CreateNoWindow = true,
        UseShellExecute = true,
        FileName = "a4.pdf"
    };
    process.Start();
}

I am looking for something that would look similar to the following HTML snippet:

<!DOCTYPE html> <html>   <head>     <meta charset="UTF-8" />     <style>       .demo {         color: white;         font-size: 40px;         -webkit-text-stroke: 1px rgb(250, 190, 255);       }     </style>   </head>   <body>     <p class="demo">The Stroked Text</p>   </body> </html>


Solution

  • You can achieve the result similar to what you have in your HTML with the following styling settings:

    p.SetStrokeColor(ColorConstants.PINK);
    p.SetStrokeWidth(0.5f);
    p.SetFontColor(ColorConstants.WHITE);
    p.SetTextRenderingMode(PdfCanvasConstants.TextRenderingMode.FILL_STROKE);
    

    Full code:

    using var doc = new PdfDocument(new PdfWriter("a4.pdf"));
    var pageSize = PageSize.A4;
    var page = doc.AddNewPage(pageSize);
    PdfCanvas pdfCanvas = new PdfCanvas(page);
    var canvas = new Canvas(pdfCanvas, pageSize);
    Paragraph p = new Paragraph("This is a Paragraph");
    p.SetFontSize(20f);
    
    p.SetStrokeColor(ColorConstants.PINK);
    p.SetStrokeWidth(0.5f);
    p.SetFontColor(ColorConstants.WHITE);
    p.SetTextRenderingMode(PdfCanvasConstants.TextRenderingMode.FILL_STROKE);
    
    canvas.ShowTextAligned(p, pageSize.GetLeft()+100, pageSize.GetTop() - 100, 1, iText.Layout.Properties.TextAlignment.LEFT, iText.Layout.Properties.VerticalAlignment.TOP, 0f);
    doc.Close();
    using (System.Diagnostics.Process process = new System.Diagnostics.Process())
    {
        process.StartInfo = new System.Diagnostics.ProcessStartInfo()
        {
            CreateNoWindow = true,
            UseShellExecute = true,
            FileName = "a4.pdf"
        };
        process.Start();
    }
    

    Visual result:

    result