在图像背景上叠加文本并转换为PDF

时间:2011-04-06 21:26:21

标签: c# .net pdf pdf-generation image-manipulation

使用.NET,我想以编程方式创建一个PDF,它只包含一个背景图像,上面有两个带有不同字体和位置的标签。我已经阅读了有关现有PDF库的内容,但不知道(如果适用)哪一个对于这样一个简单的任务最简单。

有人想引导我吗?

P.D。:我不想使用already overlays the text over the background image生成的图像创建PDF。

编辑:这是最终的工作代码:

public string Create()
{
    if (!Directory.Exists(ApplicationImagePath))
    {
        Directory.CreateDirectory(ApplicationImagePath);
    }

    // Smart card
    var doc = new Document(PageSize.GetRectangle("153 242.65"), 0, 0, 0, 0);            

    using (var stream = File.Create(filepath))
    {
       var writer = PdfWriter.GetInstance(doc, stream);

       doc.Open();

       var image = Image.GetInstance(CarnetData.Frame, ImageFormat.Png);
       image.Alignment = Element.ALIGN_CENTER;
       image.ScaleToFit(153, 242.65f);
       doc.Add(image);

       BaseFont font = BaseFont.CreateFont(GetFontPath(CarnetConfiguration.FontType), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
       font.PostscriptFontName = CarnetConfiguration.FontType.ToString();

       float verticalPosition = writer.GetVerticalPosition(false);
       var pName = new Paragraph(CarnetData.Name, new Font(font, FontData.EmployeeFont.SizeInPoints))
                        {
                            SpacingBefore = verticalPosition - 51f,
                            MultipliedLeading = 1.1f,
                            Alignment = Element.ALIGN_CENTER
                        };

        doc.Add(pName);

        var pDepartment = new Paragraph(CarnetData.Department, new Font(font, FontData.DepartmentFont.SizeInPoints))
        {
            SpacingBefore = 1.5f,
            MultipliedLeading = 1.2f,
            Alignment = Element.ALIGN_CENTER
        };

        doc.Add(pDepartment);

        writer.ViewerPreferences = PdfWriter.PageModeUseNone + PdfWriter.CenterWindow + PdfWriter.PageLayoutSinglePage;
        doc.Close();
    }

    return filepath;
}

感谢您的帮助。 :)

3 个答案:

答案 0 :(得分:0)

使用iTextSharp。免费。

答案 1 :(得分:0)

iTextSharp是一个很棒的图书馆,非常简单直观:

var doc = new Document();
using (var stream = File.Create("output.pdf"))
{
    var writer = PdfWriter.GetInstance(doc, stream);
    doc.Open();

    doc.Add(Image.GetInstance(@"c:\foo\test.png"));

    var cb = writer.DirectContent;

    cb.BeginText();
    cb.SetTextMatrix(100, 220);
    var font = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
    cb.SetFontAndSize(font, 12);
    cb.ShowText("Hello World");
    cb.EndText();

    cb.BeginText();
    cb.SetTextMatrix(100, 250);
    cb.ShowText("Some other text");
    cb.EndText();

    doc.Close();
}

答案 2 :(得分:0)

@binaryhowl - 您可以尝试使用Syncfusion PDF。它是非常好的组件,具有出色的支持

http://asp.syncfusion.com/sfaspnetsamplebrowser/9.1.0.20/Web/Pdf.Web/samples/4.0/

相关问题