change iTextSharp Font Color in c#

时间:2018-03-25 19:09:13

标签: c# pdf itext

I want to change font color. I use SetRGBColorStroke, SetColorFill, SetColorStroke but those didn't work. My code is below.

var document = new Document(PageSize.A4);
PdfReader reader2 = new PdfReader(outputPdfPath);
var stream = File.OpenWrite(path);
var writer = PdfWriter.GetInstance(document, stream);
writer.PdfVersion = PdfWriter.VERSION_1_5;
float scale = 1f;
int xs = 35; int ys = 726;
int xtemp = 0; int ytemp = 0;
document.Open();
PdfContentByte pb = writer.DirectContent;
PdfContentByte pbtext = writer.DirectContent;

for (int j = 1; j <= reader2.NumberOfPages; j++)
{
    document.NewPage();
    //PdfContentByte pbtext;
    BaseFont bf = BaseFont.CreateFont(@"C:\Windows\Fonts\arial.TTF", BaseFont.WINANSI, true);
    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();//simple read with accessible
    PdfImportedPage page = writer.GetImportedPage(reader2, j);
    pb.AddTemplate(page, scale, 0, 0, scale, xtemp, ytemp);


    if (j == 1)
    {
        Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(04.04F, 14.04F, BaseColor.BLACK, 100, -46)));
        document.Add(p);

        pbtext = writer.DirectContent;
        pbtext.BeginText();
        pbtext.SetFontAndSize(bf, 4);
        pbtext.SetRGBColorStroke(255, 0, 0);
        pbtext.ShowTextAligned(PdfContentByte.ALIGN_LEFT, namafile.Substring(0, 12), 292.0f, 740f, 0);
       // pbtext.SetColorStroke(BaseColor.RED);
       // pbtext.setColorFill(new BaseColor(255, 0, 0, 50));
       // pbtext.setColorStroke(BaseColor.RED);
        pbtext.EndText();


    }
}

//reader2.Close();

document.Close();

1 个答案:

答案 0 :(得分:1)

solved with this code:

pbtext.setColorFill(BaseColor.RED);
pbtext.ShowTextAligned(PdfContentByte.ALIGN_LEFT, namafile.Substring(0, 12), 292.0f, 740f, 0); 

my mistake put setfillcolor in bottom