Skip to content

Instantly share code, notes, and snippets.

@CodeCouturiers
Created August 8, 2024 10:22
Show Gist options
  • Save CodeCouturiers/8d13a87409a54732073ea9534376c3ef to your computer and use it in GitHub Desktop.
Save CodeCouturiers/8d13a87409a54732073ea9534376c3ef to your computer and use it in GitHub Desktop.
@CodeCouturiers
Copy link
Author

image

@CodeCouturiers
Copy link
Author

CodeCouturiers commented Aug 9, 2024

using System;
using System.IO;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Drawing;
using System.Drawing.Drawing2D;

class Program
{
    static Random random = new Random();

    static List<string> ukrainianNames = new List<string>
    {
        "Петро Іваненко", "Олена Коваленко", "Микола Шевченко", "Ірина Бондаренко", "Андрій Мельник",
        "Оксана Ткаченко", "Василь Кравченко", "Наталія Савченко", "Сергій Бойко", "Людмила Захарченко"
    };

    static string GetRandomName()
    {
        return ukrainianNames[random.Next(ukrainianNames.Count)];
    }

    static string GetRandomDate()
    {
        return $"{random.Next(1, 29):D2} {new string[] { "січня", "лютого", "березня", "квітня", "травня", "червня", "липня", "серпня", "вересня", "жовтня", "листопада", "грудня" }[random.Next(12)]} {DateTime.Now.Year}";
    }

    static string GetRandomId()
    {
        return random.Next(10000000, 99999999).ToString();
    }

    static void Main(string[] args)
    {
        // Create a document with A4 size and margins
        Document document = new Document(PageSize.A4, 30, 30, 30, 30);

        try
        {
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Договір.pdf", FileMode.Create));
            document.Open();

            // Зменшуємо розміри шрифтів
            BaseFont baseFont = BaseFont.CreateFont("C:\\Windows\\Fonts\\Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font normalFont = new iTextSharp.text.Font(baseFont, 8, iTextSharp.text.Font.NORMAL);
            iTextSharp.text.Font boldFont = new iTextSharp.text.Font(baseFont, 8, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font titleFont = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.BOLD);

            // Add a formal title section
            Paragraph title = new Paragraph("АКТ ПРИЙМАННЯ-ПЕРЕДАЧІ НАДАНИХ ПОСЛУГ/РОБІТ", titleFont);
            title.Alignment = Element.ALIGN_CENTER;
            document.Add(title);
            document.Add(new Paragraph("\n"));

            // Add header with company information
            PdfPTable headerTable = new PdfPTable(1);
            headerTable.WidthPercentage = 100;
            headerTable.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;

            // Company name and document title
            PdfPCell titleCell = new PdfPCell(new Phrase("ТОВ \"IT-РОЗРОБНИК-УКРАЇНА\"\nм. Київ", normalFont));
            titleCell.HorizontalAlignment = Element.ALIGN_CENTER;
            titleCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            titleCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            headerTable.AddCell(titleCell);

            document.Add(headerTable);
            document.Add(new Paragraph("\n"));

            // Information about date and place
            string randomDate = GetRandomDate();
            Paragraph datePlace = new Paragraph($"м. Київ                                                                     «{randomDate}»", normalFont);
            datePlace.Alignment = Element.ALIGN_RIGHT;
            document.Add(datePlace);
            document.Add(new Paragraph("\n"));

            // Main text
            string companyId = GetRandomId();
            string directorName = GetRandomName();
            string contractorName = GetRandomName();

            Paragraph mainText = new Paragraph();
            mainText.Add(new Chunk("Товариство з обмеженою відповідальністю «IT-РОЗРОБНИК-УКРАЇНА»", boldFont));
            mainText.Add(new Chunk($" (Ідентифікаційний код {companyId}), в особі директора {directorName}, який діє на підставі Статуту, іменоване надалі «Замовник», з однієї сторони, та\n", normalFont));
            mainText.Add(new Chunk($"Фізична особа-підприємець {contractorName}", boldFont));
            mainText.Add(new Chunk(", іменований надалі «Виконавець», з іншої сторони, склали цей Акт приймання-передачі наданих Послуг/Робіт (надалі – Акт) про наступне:\n\n", normalFont));
            mainText.Add(new Chunk("1. ", boldFont));
            mainText.Add(new Chunk($"На виконання Договору про надання послуг (виконання робіт) у сфері інформатизації № {random.Next(1, 100)} від «{GetRandomDate()}» Виконавець надав, а Замовник прийняв наступні Послуги/Роботи:", normalFont));
            document.Add(mainText);
            document.Add(new Paragraph("\n"));

            // Service table
            PdfPTable table = new PdfPTable(6);
            table.WidthPercentage = 100;
            table.SetWidths(new float[] { 1f, 4f, 3f, 2f, 3f, 2f });
            table.DefaultCell.Padding = 5;
            table.DefaultCell.BackgroundColor = new BaseColor(240, 240, 240);

            string[] headers = { "№", "Найменування Послуги", "Одиниця виміру", "Кількість", "Ціна за од., грн", "Сума, грн" };
            foreach (string header in headers)
            {
                PdfPCell cell = new PdfPCell(new Phrase(header, boldFont));
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell.BackgroundColor = new BaseColor(220, 220, 220);
                table.AddCell(cell);
            }

            int totalSum = 0;
            string[][] data = {
                new string[] { "1", "Послуги з розробки програмного забезпечення (72210000-0)", "година", $"{random.Next(50, 150)}", $"{random.Next(400, 800)}" },
                new string[] { "2", "Послуги з системного аналізу (72240000-9)", "година", $"{random.Next(20, 80)}", $"{random.Next(500, 900)}" },
                new string[] { "3", "Послуги з тестування програмного забезпечення (72254000-0)", "година", $"{random.Next(20, 60)}", $"{random.Next(300, 600)}" }
            };

            foreach (string[] row in data)
            {
                int quantity = int.Parse(row[3]);
                int price = int.Parse(row[4]);
                int sum = quantity * price;
                totalSum += sum;
                
                foreach (string cell in row)
                {
                    table.AddCell(new PdfPCell(new Phrase(cell, normalFont)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE });
                }
                table.AddCell(new PdfPCell(new Phrase(sum.ToString(), normalFont)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE });
            }

            document.Add(table);
            document.Add(new Paragraph("\n"));

            // Additional information
            Paragraph additionalInfo = new Paragraph();
            additionalInfo.Add(new Chunk("2. ", boldFont));
            additionalInfo.Add(new Chunk($"Загальна вартість наданих Послуг/Робіт становить {totalSum} грн ({NumberToWords(totalSum)} гривень 00 копійок), без ПДВ.\n", normalFont));
            additionalInfo.Add(new Chunk("3. ", boldFont));
            additionalInfo.Add(new Chunk("Послуги/Роботи надані в повному обсязі, своєчасно та якісно відповідно до умов Договору. Замовник претензій до обсягу, якості та строків надання Послуг/Робіт не має.\n", normalFont));
            additionalInfo.Add(new Chunk("4. ", boldFont));
            additionalInfo.Add(new Chunk("Цей Акт складено у двох примірниках, що мають однакову юридичну силу, по одному для кожної зі Сторін.", normalFont));
            document.Add(additionalInfo);
            document.Add(new Paragraph("\n"));

            // Signatures
            PdfPTable signatureTable = new PdfPTable(2);
            signatureTable.WidthPercentage = 100;
            signatureTable.SetWidths(new float[] { 1f, 1f });
            signatureTable.DefaultCell.Padding = 10;
            signatureTable.DefaultCell.BorderWidth = 1;
            signatureTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;

            PdfPCell customerCell = new PdfPCell();
            customerCell.AddElement(new Paragraph("ЗАМОВНИК", boldFont));
            customerCell.AddElement(new Paragraph("ТОВ \"IT-РОЗРОБНИК-УКРАЇНА\"", normalFont));
            customerCell.AddElement(new Paragraph($"Код ЄДРПОУ: {companyId}", normalFont));
            customerCell.AddElement(new Paragraph("Директор", normalFont));
            customerCell.AddElement(new Paragraph("\n"));

            // Add random signature for customer
            iTextSharp.text.Image customerSignature = CreateRandomSignature(directorName);
            customerCell.AddElement(customerSignature);
            
            customerCell.AddElement(new Paragraph($"____________ /{directorName}/", normalFont));
            customerCell.AddElement(new Paragraph("       м.п.", normalFont));
            customerCell.AddElement(new Paragraph("\n"));

            customerCell.BorderWidth = 1;
            customerCell.BorderColor = BaseColor.LIGHT_GRAY;
            customerCell.PaddingBottom = 20;

            PdfPCell executorCell = new PdfPCell();
            executorCell.AddElement(new Paragraph("ВИКОНАВЕЦЬ", boldFont));
            executorCell.AddElement(new Paragraph($"ФОП {contractorName}", normalFont));
            executorCell.AddElement(new Paragraph($"ІПН: {GetRandomId()}", normalFont));
            executorCell.AddElement(new Paragraph("Фізична особа-підприємець", normalFont));
            executorCell.AddElement(new Paragraph("\n"));

            // Add random signature for executor
            iTextSharp.text.Image executorSignature = CreateRandomSignature(contractorName);
            executorCell.AddElement(executorSignature);
            
            executorCell.AddElement(new Paragraph($"____________ /{contractorName}/", normalFont));
            executorCell.AddElement(new Paragraph("       м.п.", normalFont));
            executorCell.AddElement(new Paragraph("\n"));

            executorCell.BorderWidth = 1;
            executorCell.BorderColor = BaseColor.LIGHT_GRAY;
            executorCell.PaddingBottom = 20;

            signatureTable.AddCell(customerCell);
            signatureTable.AddCell(executorCell);

            document.Add(signatureTable);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            document.Close();
        }

        Console.WriteLine("PDF створено успішно.");
    }

    static iTextSharp.text.Image CreateRandomSignature(string name)
    {
        int originalWidth = 200;
        int originalHeight = 100;
        float scale = 1f; //(зменшення)
        int width = (int)(originalWidth * scale);
        int height = (int)(originalHeight * scale);

        Bitmap originalBitmap = new Bitmap(originalWidth, originalHeight);
        using (Graphics graphics = Graphics.FromImage(originalBitmap))
        {
            graphics.Clear(Color.White);

            // Create a path for the signature
            using (GraphicsPath path = new GraphicsPath())
            {
                int lastX = random.Next(10, 30);
                int lastY = random.Next(40, 60);
                int points = random.Next(15, 25);

                for (int i = 0; i < points; i++)
                {
                    int newX = random.Next(Math.Max(0, lastX - 30), Math.Min(originalWidth, lastX + 30));
                    int newY = random.Next(Math.Max(0, lastY - 20), Math.Min(originalHeight, lastY + 20));

                    int controlX = (lastX + newX) / 2 + random.Next(-20, 20);
                    int controlY = (lastY + newY) / 2 + random.Next(-20, 20);

                    path.AddBezier(lastX, lastY, controlX, controlY, controlX, controlY, newX, newY);

                    lastX = newX;
                    lastY = newY;
                }

                // Draw the signature with a gradient
                using (LinearGradientBrush brush = new LinearGradientBrush(
                    new Point(0, 0),
                    new Point(originalWidth, originalHeight),
                    Color.FromArgb(random.Next(50, 150), 0, 0, 0),
                    Color.FromArgb(random.Next(150, 256), 0, 0, 0)))
                {
                    using (Pen pen = new Pen(brush, random.Next(2, 4)))
                    {
                        graphics.DrawPath(pen, path);
                    }
                }
            }

            // Add a decorative underline
            using (Pen underlinePen = new Pen(Color.FromArgb(100, 0, 0, 0), 1))
            {
                underlinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
                graphics.DrawLine(underlinePen, 10, originalHeight - 10, originalWidth - 10, originalHeight - 10);
            }

            // Add initials with shadow
            using (System.Drawing.Font font = new System.Drawing.Font("Arial", 14, FontStyle.Bold))
            {
                string[] nameParts = name.Split(' ');
                string initials = $"{nameParts[0][0]}.{nameParts[1][0]}.";

                // Draw shadow
                using (SolidBrush shadowBrush = new SolidBrush(Color.FromArgb(50, 0, 0, 0)))
                {
                    graphics.DrawString(initials, font, shadowBrush, originalWidth - 52, originalHeight - 32);
                }

                // Draw initials
                using (SolidBrush brush = new SolidBrush(Color.FromArgb(200, 0, 0, 0)))
                {
                    graphics.DrawString(initials, font, brush, originalWidth - 50, originalHeight - 30);
                }
            }
        }

        // Scale down the image
        Bitmap scaledBitmap = new Bitmap(width, height);
        using (Graphics graphics = Graphics.FromImage(scaledBitmap))
        {
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(originalBitmap, 0, 0, width, height);
        }

        MemoryStream ms = new MemoryStream();
        scaledBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return iTextSharp.text.Image.GetInstance(ms.ToArray());
    }


    static string NumberToWords(int number)
    {
        // This is a simplified version. For a full implementation, you'd need a more complex algorithm.
        string[] units = { "", "одна", "дві", "три", "чотири", "п'ять", "шість", "сім", "вісім", "дев'ять" };
        string[] teens = { "десять", "одинадцять", "дванадцять", "тринадцять", "чотирнадцять", "п'ятнадцять", "шістнадцять", "сімнадцять", "вісімнадцять", "дев'ятнадцять" };
        string[] tens = { "", "", "двадцять", "тридцять", "сорок", "п'ятдесят", "шістдесят", "сімдесят", "вісімдесят", "дев'яносто" };
        string[] thousands = { "", "тисяча", "тисячі", "тисяч" };

        if (number == 0)
            return "нуль";

        if (number < 0)
            return "мінус " + NumberToWords(Math.Abs(number));

        string words = "";

        if ((number / 1000) > 0)
        {
            words += NumberToWords(number / 1000) + " " + thousands[(number / 1000) % 10] + " ";
            number %= 1000;
        }

        if ((number / 100) > 0)
        {
            words += units[number / 100] + "сот ";
            number %= 100;
        }

        if (number >= 20)
        {
            words += tens[number / 10] + " ";
            number %= 10;
        }

        if (number >= 10)
        {
            words += teens[number - 10] + " ";
            return words;
        }

        if (number > 0)
        {
            words += units[number] + " ";
        }

        return words.Trim();
    }
}

@CodeCouturiers
Copy link
Author

image
image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment