使用itextsharp(asp.net,C#)在pdf中添加图像上方和下方的文本

时间:2016-05-26 07:03:14

标签: c# asp.net itextsharp

我已使用memorystream将图像转换为byte[],然后使用itextsharp将byte[]添加到pdf。 现在我的要求是在图像上方添加一些文本,提供有关图像的一些信息。

这是我的代码

private void generatepdf(byte[] byteImage)
    {
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(byteImage);
    image.ScalePercent(0.3f * 100);
    using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
    {
        Document document = new Document(PageSize.A4, 188f, 88f, 10f, 10f);
        PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
        document.Open();
        document.Add(image);
        document.Close();
        byte[] bytes = memoryStream.ToArray();
        memoryStream.Close();

        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
        Response.ContentType = "application/pdf";
        Response.Buffer = true;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(bytes);
        Response.End();
    } 

如何添加一些文本并转换为字节,然后将其发送到pdf对象。或者有没有更好的方法来指导我正确的方向。

1 个答案:

答案 0 :(得分:2)

你可以这样尝试

        private void generatepdf(byte[] byteImage)
        {
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(byteImage);
            image.ScalePercent(0.3f * 100);
            using (MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                Document document = new Document(PageSize.A4, 188f, 88f, 10f, 10f);
                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);

                string text1 = "before image";
                Paragraph text1Title = new Paragraph(text1);

                string text2 = "after image";
                Paragraph text2Title = new Paragraph(text2);

                document.Open();
                document.Add(text1Title);
                document.Add(image);
                document.Add(text2Title);
                document.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();

                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
            }
        }