C Generates PDF File Stream
- 2021-12-12 05:23:46
- OfStack
This article example for everyone to share C # generated PDF file stream specific code, for your reference, the specific content is as follows
1. Set the font
static BaseFont FontBase = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
static iTextSharp.text.Font bodyFont = new iTextSharp.text.Font(FontBase, 12);
static iTextSharp.text.Font titleFont = new iTextSharp.text.Font(FontBase, 18);
static iTextSharp.text.Font paragraphFont = new iTextSharp.text.Font(FontBase, 15);
static iTextSharp.text.Font linkFont = new iTextSharp.text.Font(FontBase, 12, Font.UNDERLINE, BaseColor.BLUE);
2. Generate an PDF file stream to return an byte array
public byte[] DocCreate(System.Drawing.Image image, List<TreeNodes> list)
{
MemoryStream file = new MemoryStream();
string fileName = string.Empty;
Rectangle page = PageSize.A4;
float y = page.Height;
Document document = new Document(page, 15, 15, 30, 30);
float docWidth = page.Width - 15 * 2;
float docHeight = page.Height - document.BottomMargin - document.TopMargin;
PdfWriter writer = PdfWriter.GetInstance(document, file);
writer.CloseStream = false;
writer.Open();
PdfContentByte cb = writer.DirectContent;
document.Open();
// Title
Paragraph title = new Paragraph(new Chunk(" Title ", titleFont));
title.Alignment = Element.ALIGN_CENTER;
document.Add(title);
// Picture
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(image, ImageFormat.Png);
float widthSzie = (page.Width - 30) / img.Width;
if (widthSzie < 1)
{
img.ScalePercent(widthSzie * 100);
}
document.Add(img);
// Document source
Paragraph p2 = new Paragraph(new Chunk(" Source ", paragraphFont));
p2.IndentationLeft = indentationLeft;
document.Add(p2);
InitData(list);// Initialize business data
CreateSteps(list, document, list.FirstOrDefault(it => it.PID == 0));// Add business data
//// Add a seal
//iTextSharp.text.Image whyz = iTextSharp.text.Image.GetInstance(whyzPath);
//whyz.ScalePercent(50);
//whyz.PaddingTop = 100;
//whyz.Alignment = Element.ALIGN_RIGHT;
//document.Add(whyz);
// Add date
Paragraph createtime = new Paragraph(new Chunk(DateTime.Now.ToLongDateString().ToString(), bodyFont));
createtime.Alignment = Element.ALIGN_RIGHT;
//createtime.SpacingBefore = -80;
createtime.PaddingTop = 200;
document.Add(createtime);
document.Close();
file.Position = 0;
MemoryStream newfile = SetWaterMark(file, " Watermark content ", docWidth, docHeight);// To add a watermark, see Additional 1 A blog
newfile.Position = 0;// Reset the stream pointer position
byte[] bytes = new byte[newfile.Length];
newfile.Read(bytes, 0, bytes.Length);
return bytes;
}