COP_Petrushin_PIbd-32/Library14Petrushin/PdfImg.cs
2024-10-01 10:26:35 +04:00

61 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
namespace Library14Petrushin
{
public partial class PdfImg : Component
{
public PdfImg()
{
InitializeComponent();
}
public PdfImg(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreatePdfDocument(string fileName, string documentTitle, List<ImageData> images)
{
if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(documentTitle) || images == null || images.Count == 0)
{
throw new ArgumentException("Все входные данные должны быть заполнены.");
}
PdfDocument document = new PdfDocument();
PdfPage firstPage = document.AddPage();
XGraphics gfxFirstPage = XGraphics.FromPdfPage(firstPage);
XFont font = new XFont("Arial", 20, XFontStyleEx.BoldItalic);
gfxFirstPage.DrawString(documentTitle, font, XBrushes.Black, new XRect(0, 0, firstPage.Width, 50), XStringFormats.Center);
foreach (var imageData in images)
{
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
using (XImage img = XImage.FromFile(imageData.ImagePath))
{
double imageWidth = img.PixelWidth * 72 / img.HorizontalResolution;
double imageHeight = img.PixelHeight * 72 / img.VerticalResolution;
double scale = Math.Min(page.Width / imageWidth, page.Height / imageHeight);
gfx.DrawImage(img, 0, 0, imageWidth * scale, imageHeight * scale);
}
}
document.Save(fileName);
}
}
public class ImageData
{
public string ImagePath { get; set; }
}
}