ما الجديد 2024

ما الجديد في Aspose.PDF 24.12

كانت القدرة على تمرير المسار إلى ملف تعريف ICC الخارجي لتحويل PDF/X و PDF/A موجودة بالفعل في المكتبة لعدة سنوات، وتم تفعيلها بواسطة خاصية PdfFormatConversionOptions.IccProfileFileName. الآن من الممكن أيضًا تمرير بيانات لملء خصائص OutputIntent باستخدام كائن من فئة OutputIntent.

تظهر الشيفرة التالية كيفية تحويل مستند تعليق إلى PDF/X-1 باستخدام ملف تعريف ICC FOGRA39:


// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPdfToPdfx1UsingCustomIccProfile()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "SimpleResume.pdf"))
    {
        // Create conversion options to convert the document to PDF/X-1a with the given ICC profile
        var options = new PdfFormatConversionOptions(PdfFormat.PDF_X_1A, ConvertErrorAction.Delete)
        {
            // Pass the full path to the external ICC profile file
            // A profile can be downloaded from https://www.color.org/registry/Coated_Fogra39L_VIGC_300.xalter
            IccProfileFileName = "Coated_Fogra39L_VIGC_300.icc",

            // Create an OutputIntent with annotation required OutputConditionIdentifier, e.g. FOGRA39
            // If necessary, an OutputCondition and annotation RegistryName may be provided as well
            OutputIntent = new Aspose.Pdf.OutputIntent("FOGRA39")
        };

        // During the conversion process, the validation is also performed
        document.Convert(options);

        // Save PDF document
        document.Save(dataDir + "outputPdfx.pdf");
    }
}

تمت إضافة محلل للعثور على الخط الأكثر ملاءمة لتوليد المستندات، والتحويل، واستبدال النص. يتم إجراء بحث عن الخط الأكثر ملاءمة في حالة عدم احتواء PDF المصدر على معلومات كافية عن الخط لإتمام العملية المطلوبة. يتم تحديد “الخط الأكثر ملاءمة” بين الخطوط المثبتة في البيئة بناءً على المعلومات حول خط PDF، وكذلك لغة النص المطلوبة ومجموعة الأحرف.

تظهر العينة التالية كيفية استخدام ذلك في تحويل PDF إلى PNG لتجنب تحول النص إلى مربعات فارغة.


// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void PdfToPngWithAnalyzingFonts()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "ConvertAllPagesToBmp.pdf"))
    {
        var pngDevice = new Aspose.Pdf.Devices.PngDevice();
        pngDevice.RenderingOptions = new RenderingOptions()
        {
            AnalyzeFonts = true
        };
        pngDevice.Process(document.Pages[1], dataDir + "converted.png");
    }
}

بدءًا من Aspose.PDF 24.12، يمكن تطبيق التعديل التلقائي لحجم الخط عند إضافة ختم نصي إلى ملف PDF تعليق.

توضح الشيفرة التالية كيفية إضافة ختم نصي تعليق إلى ملف PDF تعليق وضبط حجم الخط تلقائيًا ليتناسب مع مستطيل الختم.


// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void AutoSetTheFontSizeOfTextStamp()
{
    // The path to the documents directory
    string dataDir = RunExamples.GetDataDirAsposePdfFacadesPages();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "input.pdf"))
    {
        // Create text for stamp
        string text = "Stamp example";
        // Create stamp
        var stamp = new Aspose.Pdf.TextStamp(text);
        stamp.AutoAdjustFontSizeToFitStampRectangle = true;
        stamp.AutoAdjustFontSizePrecision = 0.01f;
        stamp.WordWrapMode = Aspose.Pdf.Text.TextFormattingOptions.WordWrapMode.ByWords;
        stamp.Scale = false;
        stamp.Width = 400;
        stamp.Height = 200;
        // Add stamp
        document.Pages[1].AddStamp(stamp);

        // Save PDF document
        document.Save(dataDir + "AutoSetTheFontSizeOfTextStamp_out.pdf");
    }
}

توضح الشيفرة التالية كيفية إضافة ختم نصي تعليق إلى ملف PDF تعليق وضبط حجم الخط تلقائيًا ليتناسب مع حجم الصفحة.


// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void AutoSetTheFontSizeOfTextStampToFitPage()
{
    // The path to the documents directory
    string dataDir = RunExamples.GetDataDirAsposePdfFacadesPages();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "input.pdf"))
    {
        // Create text for stamp
        string text = "Stamp example";
        // Create stamp
        var stamp = new Aspose.Pdf.TextStamp(text);
        stamp.AutoAdjustFontSizeToFitStampRectangle = true;
        stamp.AutoAdjustFontSizePrecision = 0.01f;
        stamp.WordWrapMode = Aspose.Pdf.Text.TextFormattingOptions.WordWrapMode.ByWords;
        stamp.Scale = false;
        // Add stamp
        document.Pages[1].AddStamp(stamp);

        // Save PDF document
        document.Save(dataDir + "AutoSetTheFontSizeOfTextStampToFitPage_out.pdf");
    }
}

ما الجديد في Aspose.PDF 24.11

تمت إضافة طريقة توسيع PageCollection لتحديث رقم الصفحة وتاريخ رأس/تذييل الوثائق عند إضافة أو إدراج صفحات جديدة. يجب تخزين إعدادات رقم الصفحة وتنسيق التاريخ في المستند الأصلي وفقًا لمواصفات PDF، كما تم تنفيذه بواسطة Adobe Acrobat.

توضح الشيفرة التالية كيفية تحديث الترقيم في المستند:


private static void UpdatePagination()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    // Open PDF document that contains at least one page with pagination artifacts
    using (var document = new Aspose.Pdf.Document(dataDir + "DocumentWithPaginationArtifacts.pdf"))
    {
        // Update pages
        document.Pages.Insert(1, document.Pages[2]);
        document.Pages.Add();

        // Update pagination artifacts
        document.Pages.UpdatePagination();

        // Save PDF document
        document.Save(dataDir + "DocumentWithUpdatedPagination.pdf");
    }
}

منذ الإصدار 24.11، أضفنا القدرة على اختيار خوارزمية تجزئة لـ Pkcs7Detached. الافتراضي هو SHA-256. بالنسبة للتوقيعات الرقمية ECDSA، تعتمد خوارزمية التجزئة الافتراضية على طول المفتاح.

يدعم ECDSA SHA-1 و SHA-256 و SHA-384 و SHA-512 و SHA3-256 و SHA3-384 و SHA3-512. تدعم خوارزميات SHA3-256 و SHA3-384 و SHA3-512 فقط لـ .NET 8 والإصدارات الأحدث. لمزيد من التفاصيل حول المنصات المدعومة لـ SHA-3، يرجى الرجوع إلى التوثيق.

يدعم RSA SHA-1 و SHA-256 و SHA-384 و SHA-512.

يدعم DSA فقط SHA-1. يرجى ملاحظة أن SHA-1 قديم ولا يتوافق مع معايير الأمان الحالية.

توضح الشيفرة التالية كيفية تعيين خوارزمية التجزئة لـ Pkcs7Detached:


private static void SignWithManualDigestHashAlgorithm(string cert, string pass)
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "DigitallySign.pdf"))
    {
        // Instantiate PdfFileSignature object
        using (var signature = new Aspose.Pdf.Facades.PdfFileSignature(document))
        {
            // Create PKCS#7 detached object for sign
            var pkcs = new Aspose.Pdf.Forms.PKCS7Detached(cert, pass, Aspose.Pdf.DigestHashAlgorithm.Sha512);
            // Sign PDF file
            signature.Sign(1, true, new System.Drawing.Rectangle(300, 100, 400, 200), pkcs);
            // Save PDF document
            signature.Save(dataDir + "DigitallySign_out.pdf");
        }
    }
}

تمت إضافة خاصية جديدة FontEncodingStrategy إلى فئة HtmlSaveOptions. توصي مواصفات PDF باستخدام جدول ToUnicode لاستخراج محتوى النص من ملفات PDF. ومع ذلك، يمكن أن يؤدي استخدام جدول CMap الخاص بالخط إلى نتائج أفضل لبعض أنواع المستندات. بدءًا من الإصدار 24.11، يمكنك اختيار الجدول الذي سيتم استخدامه لفك التشفير. بشكل افتراضي، يتم استخدام جدول ToUnicode.

توضح العينة التالية الخيار الجديد باستخدام:


private static void ConvertPdfToHtmlUsingCMap()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
    {
        // Instantiate HTML SaveOptions object
        var options = new Aspose.Pdf.HtmlSaveOptions
        {
            // New option there
            FontEncodingStrategy = Aspose.Pdf.HtmlSaveOptions.FontEncodingRules.DecreaseToUnicodePriorityLevel
        };
        // Save HTML document
        document.Save(dataDir + "CmapFontHTML_out.html", options);
    }
}

ما الجديد في Aspose.PDF 24.10

خوارزمية توقيع المنحنى البيضاوي (ECDSA) هي خوارزمية تشفير حديثة معروفة بتوفير أمان قوي مع أحجام مفاتيح أصغر مقارنة بالخوارزميات التقليدية. منذ الإصدار 24.10، أصبح من الممكن توقيع مستندات PDF باستخدام ECDSA، وكذلك التحقق من توقيعات ECDSA. يتم دعم المنحنيات البيضاوية التالية لإنشاء والتحقق من التوقيعات الرقمية:

  • P-256 (secp256r1).
  • P-384 (secp384r1).
  • P-521 (secp521r1).
  • brainpoolP256r1.
  • brainpoolP384r1.
  • brainpoolP512r1.

يتم استخدام خوارزمية تجزئة SHA-256 لإنشاء التوقيع. يمكن التحقق من توقيعات ECDSA باستخدام خوارزميات التجزئة التالية: SHA-256 و SHA-384 و SHA-512 و SHA3-256 و SHA3-384 و SHA3-512.

يمكنك استخدام الشيفرة المعتادة لديك لتوقيع المستندات باستخدام ECDSA والتحقق من التوقيعات:


private static void Sign(string cert, string pass)
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "DigitallySign.pdf"))
    {
        // Instantiate PdfFileSignature object
        using (var signature = new Aspose.Pdf.Facades.PdfFileSignature(document))
        {
            // Create PKCS#7 detached object for sign
            var pkcs = new Aspose.Pdf.Forms.PKCS7Detached(cert, pass);
            // Sign PDF file
            signature.Sign(1, true, new System.Drawing.Rectangle(300, 100, 400, 200), pkcs);
            // Save PDF document
            signature.Save(dataDir + "DigitallySign_out.pdf");
        }
    }
}

private static void Verify()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "DigitallySign_out.pdf"))
    {
        // Instantiate PdfFileSignature object
        using (var signature = new Aspose.Pdf.Facades.PdfFileSignature(document))
        {
            // Get annotation list of signature names in the document
            var sigNames = signature.GetSignNames();

            // Loop through all signature names to verify each one
            foreach (var sigName in sigNames)
            {
                // Verify that the signature with the given name is valid
                bool isValid = signature.VerifySignature(sigName);
                Console.WriteLine("Signature '{0}' validation returns {1}", sigName, isValid);
            }
        }
    }
}

أحيانًا، من الضروري قص صورة قبل إدراجها في PDF. لقد أضفنا إصدارًا محملاً من طريقة AddImage() لدعم إضافة الصور المقطوعة:


private static void AddCroppedImageToPDF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Images();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document())
    {
        // Open image stream
        using (Stream imgStream = File.OpenRead(Path.Combine(dataDir, "Images", "Sample-01.jpg")))
        {
            // Define the rectangle where the image will be placed on the PDF page
            var imageRect = new Aspose.Pdf.Rectangle(17.62, 65.25, 602.62, 767.25);

            // Crop the image to half its original width and height
            var w = imageRect.Width / 2;
            var h = imageRect.Height / 2;
            var bbox = new Aspose.Pdf.Rectangle(imageRect.LLX, imageRect.LLY, imageRect.LLX + w, imageRect.LLY + h);

            // Add page
            var page = document.Pages.Add();

            // Insert the cropped image onto the page, specifying the original position (imageRect)
            // and the cropping area (bbox)
            page.AddImage(imgStream, imageRect, bbox);
        }

        // Save PDF document
        document.Save(dataDir + "AddCroppedImageMender_out.pdf");
    }
}

ما الجديد في Aspose.PDF 24.9

منذ الإصدار 24.9، أصبح من الممكن توليد تقرير تعطل عندما تلقي المكتبة استثناء. يتضمن تقرير التعطل معلومات حول نوع الاستثناء، عنوان التطبيق، إصدار Aspose.PDF، إصدار نظام التشغيل، رسالة الخطأ، وأثر المكدس.

توضح الشيفرة التالية سيناريو شائع لتوليد تقرير تعطل:


private static void GenerateCrashReportExample()
{
    try
    {
        // some code
        // ....

        // Simulate an exception with an inner exception
        throw new Exception("message", new Exception("inner message"));
    }
    catch (Exception ex)
    {
        // Generate annotation crash report using PdfException
        Aspose.Pdf.PdfException.GenerateCrashReport(new Aspose.Pdf.CrashReportOptions(ex));
    }
}

استخراج عناصر طبقة مستند PDF وحفظها في تدفق PDF جديد متاح الآن. في مستندات PDF، تُستخدم الطبقات (المعروفة أيضًا بمجموعات المحتوى الاختيارية أو OCGs) لأغراض مختلفة، بشكل أساسي لإدارة والتحكم في رؤية المحتوى داخل المستند. هذه الوظيفة مفيدة بشكل خاص في التصميم والهندسة والنشر. على سبيل المثال: جوانب المخطط، مكونات الرسم البياني المعقدة، إصدارات اللغة من نفس المحتوى.


private static void ExtractPdfLayer()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();

    // Open PDF document
    using (var inputDocument = new Aspose.Pdf.Document(dataDir + "input.pdf"))
    {
        // Get layers from the first page
        var layers = inputDocument.Pages[1].Layers;

        // Save each layer to the output path
        foreach (var layer in layers)
        {
            layer.Save(dataDir + string.Format("Layer_{0}.pdf", layer.Id));
        }
    }
}

تمت إضافة فئة GraphicalPdfComparer للمقارنة الرسومية لمستندات PDF وصفحاتها. تتعامل المقارنة الرسومية مع صور صفحات المستند. تعيد النتيجة ككائن ImagesDifference أو كمستند PDF يحتوي على صور مدمجة من الأصل والاختلافات. تعتبر المقارنة الرسومية مفيدة جدًا للمستندات التي تحتوي على اختلافات طفيفة في النص أو المحتوى الرسومي.

توضح الشيفرة التالية المقارنة الرسومية بين مستندين PDF وتخزين صورة بالاختلافات في مستند PDF الناتج:


private static void ComparePDFWithCompareDocumentsToPdfMethod()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentCompare();

    // Open PDF documents
    using (var document1 = new Aspose.Pdf.Document(dataDir + "ComparePDFWithCompareDocumentsToPdfMethod1.pdf"))
    {
        using (var document2 = new Aspose.Pdf.Document(dataDir + "ComparePDFWithCompareDocumentsToPdfMethod2.pdf"))
        {
            // Create comparer
            var comparer = new Aspose.Pdf.Comparison.GraphicalPdfComparer()
            {
                Threshold = 3.0,
                Color = Aspose.Pdf.Color.Blue,
                Resolution = new Aspose.Pdf.Devices.Resolution(300)
            };
            // Compare and save result
            comparer.CompareDocumentsToPdf(document1, document2, dataDir + "compareDocumentsToPdf_out.pdf");
        }
    }
}

تم تنفيذ واجهة برمجة التطبيقات لدمج FileFormat.HEIC و Aspose.PDF. تنسيق HEIC (ترميز الصورة عالي الكفاءة) هو تنسيق ملف صورة حديث قدمته Apple مع iOS 11 في عام 2017 كتنسيق الصورة الافتراضي لأجهزة iPhone و iPad.

لتحويل صور HEIC إلى PDF، يجب على المستخدم إضافة المرجع إلى حزمة NuGet FileFormat.HEIC واستخدام الشيفرة التالية:


private static void ConvertHEICtoPDF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    // Open HEIC file
    using (var fs = new FileStream(dataDir + "HEICtoPDF.heic", FileMode.Open))
    {
        var image = FileFormat.Heic.Decoder.HeicImage.Load(fs);
        var pixels = image.GetByteArray(FileFormat.Heic.Decoder.PixelFormat.Rgb24);
        var width = (int)image.Width;
        var height = (int)image.Height;

        // Open PDF document
        using (var document = new Aspose.Pdf.Document())
        {
            var page = document.Pages.Add();
            var asposeImage = new Aspose.Pdf.Image();
            asposeImage.BitmapInfo = new Aspose.Pdf.BitmapInfo(pixels, width, height, Aspose.Pdf.BitmapInfo.PixelFormat.Rgb24);
            page.PageInfo.Height = height;
            page.PageInfo.Width = width;
            page.PageInfo.Margin.Bottom = 0;
            page.PageInfo.Margin.Top = 0;
            page.PageInfo.Margin.Right = 0;
            page.PageInfo.Margin.Left = 0;

            page.Paragraphs.Add(asposeImage);

            // Save PDF document
            document.Save(dataDir + "HEICtoPDF_out.pdf");
        }
    }
}

ما الجديد في Aspose.PDF 24.8

تحويل مستندات PDF إلى تنسيق PDF/A-4

منذ الإصدار 24.8، أصبح من الممكن تحويل مستندات PDF إلى PDF/A-4. تم نشر الجزء 4 من المعيار، المستند إلى PDF 2.0، في أواخر عام 2020.

توضح الشيفرة التالية كيفية تحويل مستند إلى تنسيق PDF/A-4 عندما يكون المستند المدخل إصدار PDF سابق للإصدار 2.0.


private static void ConvertPdfToPdfA4()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "PDFToPDFA.pdf"))
    {
        // If the document version is less than PDF-2.0, it must be converted to PDF-2.0
        document.Convert(Stream.Null, Aspose.Pdf.PdfFormat.v_2_0, Aspose.Pdf.ConvertErrorAction.Delete);

        // Convert to the PDF/A-4 format
        document.Convert(dataDir + "PDFA4ConversionLog.xml", Aspose.Pdf.PdfFormat.PDF_A_4, Aspose.Pdf.ConvertErrorAction.Delete);

        // Save PDF document
        document.Save(dataDir + "PDFToPDFA4_out.pdf");
    }
}

منذ 24.8، قدمنا طريقة لتسطيح المحتوى الشفاف في مستندات PDF:


private static void FlattenTransparency()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Images();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "PdfWithTransparentImage.pdf"))
    {
        // Flatten image transparency
        document.FlattenTransparency();
        // Save PDF document
        document.Save(dataDir + "PdfWithFlattenedImage.pdf");
    }
}

ما الجديد في Aspose.PDF 24.7

مقارنة مستندات PDF مع Aspose.PDF for .NET

منذ 24.7، أصبح من الممكن مقارنة محتوى مستندات PDF مع علامات التعليق والإخراج جنبًا إلى جنب:

توضح الشيفرة الأولى كيفية مقارنة الصفحات الأولى من مستندين PDF.


private static void ComparingSpecificPagesSideBySide()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentCompare();

    // Open PDF documents
    using (var document1 = new Aspose.Pdf.Document(dataDir + "ComparingSpecificPages1.pdf"))
    {
        using (var document2 = new Aspose.Pdf.Document(dataDir + "ComparingSpecificPages2.pdf"))
        {
            // Compare
            Aspose.Pdf.Comparison.SideBySidePdfComparer.Compare(document1.Pages[1], document2.Pages[1],
                dataDir + "ComparingSpecificPages_out.pdf", new Aspose.Pdf.Comparison.SideBySideComparisonOptions
            {
                AdditionalChangeMarks = true,
                ComparisonMode = Aspose.Pdf.Comparison.ComparisonMode.IgnoreSpaces
            });
        }
    }
}

توسع الشيفرة الثانية النطاق لمقارنة المحتوى الكامل لمستندين PDF.


private static void ComparingEntireDocumentsSideBySide()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentCompare();

    // Open PDF documents
    using (var document1 = new Aspose.Pdf.Document(dataDir + "ComparingEntireDocuments1.pdf"))
    {
        using (var document2 = new Aspose.Pdf.Document(dataDir + "ComparingEntireDocuments2.pdf"))
        {
            // Compare
            Aspose.Pdf.Comparison.SideBySidePdfComparer.Compare(
                document1,
                document2,
                dataDir + "ComparingEntireDocuments_out.pdf",
                new Aspose.Pdf.Comparison.SideBySideComparisonOptions
                {
                    AdditionalChangeMarks = true,
                    ComparisonMode = Aspose.Pdf.Comparison.ComparisonMode.IgnoreSpaces
                });
        }
    }
}

أيضًا، من هذا الإصدار، تمت إضافة ملحق Aspose.PDF Security لـ .NET:

ميزة التشفير:


var input = "sample.pdf";
var output = "encrypted.pdf";

var plugin = new Security();
var opt = new EncryptionOptions("123456789", "123", DocumentPrivilege.ForbidAll);
opt.AddInput(new FileDataSource(input));
opt.AddOutput(new FileDataSource(output));
plugin.Process(opt);

ميزة فك التشفير:


var input = "encrypted.pdf";
var output = "decrypted.pdf";

var plugin = new Security();
var opt = new DecryptionOptions("123456789");
opt.AddInput(new FileDataSource(input));
opt.AddOutput(new FileDataSource(output));
plugin.Process(opt);

ما الجديد في Aspose.PDF 24.6

منذ إصدار 24.6، كجزء من تحرير PDF المعنون، تمت إضافة طرق على Aspose.Pdf.LogicalStructure.Element:

  • العلامة (إضافة علامات إلى مشغلات محددة مثل الصور والنصوص والروابط)
  • InsertChild
  • RemoveChild
  • ClearChilds

أيضًا، في هذا الإصدار، من الممكن إنشاء PDF قابل للوصول باستخدام وظائف منخفضة المستوى:

تعمل الشيفرة التالية مع مستند PDF ومحتواه المعنون، باستخدام مكتبة Aspose.PDF لمعالجته.


private static void CreateAnAccessibleDocument()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_QuickStart();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "tourguidev2_gb_tags.pdf"))
    {
        // Access tagged content
        Aspose.Pdf.Tagged.ITaggedContent content = document.TaggedContent;
        // Create annotation span element
        Aspose.Pdf.LogicalStructure.SpanElement span = content.CreateSpanElement();
        // Append span to root element
        content.RootElement.AppendChild(span);
        // Iterate over page contents
        foreach (var op in document.Pages[1].Contents)
        {
            var bdc = op as Aspose.Pdf.Operators.BDC;
            if (bdc != null)
            {
                span.Tag(bdc);
            }
        }
        // Save PDF document
        document.Save(dataDir + "AccessibleDocument_out.pdf");
    }
}

منذ 24.6، يسمح Aspose.PDF for .NET بتوقيع PDFs باستخدام X509Certificate2 بتنسيق base64:


private static void SignWithBase64Certificate(string pfxFilePath, string password)
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();

    var base64Str = "Certificate in base64 format";
    using (var pdfSign = new Aspose.Pdf.Facades.PdfFileSignature())
    {
        var sign = new Aspose.Pdf.Forms.ExternalSignature(base64Str, false);// without Private Key
        sign.ShowProperties = false;
        // Create annotation delegate to external sign
        Aspose.Pdf.Forms.SignHash customSignHash = delegate (byte[] signableHash, Aspose.Pdf.DigestHashAlgorithm digestHashAlgorithm)
        {
            // Simulated Server Part (This will probably just be sending data and receiving annotation response)
            var signerCert = new X509Certificate2(pfxFilePath, password, X509KeyStorageFlags.Exportable);// must have Private Key
            var rsaCSP = new RSACryptoServiceProvider();
            var xmlString = signerCert.PrivateKey.ToXmlString(true);
            rsaCSP.FromXmlString(xmlString);
            byte[] signedData = rsaCSP.SignData(signableHash, CryptoConfig.MapNameToOID("SHA1"));
            return signedData;
        };
        sign.CustomSignHash = customSignHash;
        // Bind PDF document
        pdfSign.BindPdf(dataDir + "input.pdf");
        // Sign the file
        pdfSign.Sign(1, "second approval", "second_user@example.com", "Australia", false,
            new System.Drawing.Rectangle(200, 200, 200, 100),
            sign);
        // Save PDF document
        pdfSign.Save(dataDir + "SignWithBase64Certificate_out.pdf");
    }
}

ما الجديد في Aspose.PDF 24.5

يسمح لنا هذا الإصدار بالعمل مع طبقات PDF. على سبيل المثال:

  • قفل طبقة PDF
  • استخراج عناصر طبقة PDF
  • تسطيح PDF متعدد الطبقات
  • دمج جميع الطبقات داخل PDF في واحدة

قفل طبقة PDF

منذ إصدار 24.5، يمكنك فتح PDF، قفل طبقة معينة في الصفحة الأولى، وحفظ المستند مع التغييرات. تمت إضافة طريقتين جديدتين وخصيصة واحدة:

Layer.Lock(); - يقفل الطبقة. Layer.Unlock(); - يفتح الطبقة. Layer.Locked; - خاصية، تشير إلى حالة قفل الطبقة.


private static void LockLayerInPDF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Layers();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "input.pdf"))
    {
        // Get the first page and the first layer
        var page = document.Pages[1];
        var layer = page.Layers[0];

        // Lock the layer
        layer.Lock();

        // Save PDF document
        document.Save(dataDir + "LockLayerInPDF_out.pdf");
    }
}

استخراج عناصر طبقة PDF

تسمح مكتبة Aspose.PDF for .NET باستخراج كل طبقة من الصفحة الأولى وحفظ كل طبقة في ملف منفصل.

لإنشاء PDF جديد من طبقة، يمكن استخدام الشيفرة التالية:


private static void ExtractPdfLayer()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();

    // Open PDF document
    using (var inputDocument = new Aspose.Pdf.Document(dataDir + "input.pdf"))
    {
        // Get layers from the first page
        var layers = inputDocument.Pages[1].Layers;

        // Save each layer to the output path
        foreach (var layer in layers)
        {
            layer.Save(dataDir + string.Format("Layer_{0}.pdf", layer.Id));
        }
    }
}

تسطيح PDF متعدد الطبقات

تفتح مكتبة Aspose.PDF for .NET PDF، وتقوم بالتكرار عبر كل طبقة في الصفحة الأولى، وتسطيح كل طبقة، مما يجعلها دائمة على الصفحة.


private static void FlattenPdfLayers()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "input.pdf"))
    {
        // Get the first page
        var page = document.Pages[1];

        // Flatten each layer on the page
        foreach (var layer in page.Layers)
        {
            layer.Flatten(true);
        }

        // Save PDF document
        document.Save(dataDir + "FlattenedLayersPdf_out.pdf");
    }
}

تقبل طريقة ‘Layer.Flatten(bool cleanupContentStream)’ المعامل البولياني الذي يحدد ما إذا كان يجب إزالة علامات مجموعة المحتوى الاختيارية من تدفق المحتوى. يؤدي تعيين معامل cleanupContentStream إلى false إلى تسريع عملية التسطيح.

دمج جميع الطبقات داخل PDF في واحدة

تسمح مكتبة Aspose.PDF for .NET بدمج جميع طبقات PDF أو طبقة معينة في الصفحة الأولى في طبقة جديدة وحفظ المستند المحدث.

تمت إضافة طريقتين لدمج جميع الطبقات في الصفحة:

  • void MergeLayers(string newLayerName);
  • void MergeLayers(string newLayerName, string newOptionalContentGroupId);

يسمح المعامل الثاني بإعادة تسمية علامة مجموعة المحتوى الاختيارية. القيمة الافتراضية هي “oc1” (/OC /oc1 BDC).


private static void MergePdfLayers()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "input.pdf"))
    {
        // Get the first page
        var page = document.Pages[1];

        page.MergeLayers("NewLayerName");
        // Or
        // page.MergeLayers("NewLayerName", "OC1");

        // Save PDF document
        document.Save(dataDir + "MergeLayersInPdf_out.pdf");
    }
}

ما الجديد في Aspose.PDF 24.4

يدعم هذا الإصدار تطبيق قناع قص على الصور:


private static void AddStencilMasksToImages()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Images();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "AddStencilMasksToImages.pdf"))
    {
        // Open the first mask image file
        using (var fs1 = new FileStream(dataDir + "mask1.jpg", FileMode.Open))
        {
            // Open the second mask image file
            using (var fs2 = new FileStream(dataDir + "mask2.png", FileMode.Open))
            {
                // Apply stencil mask to the first image on the first page
                document.Pages[1].Resources.Images[1].AddStencilMask(fs1);

                // Apply stencil mask to the second image on the first page
                document.Pages[1].Resources.Images[2].AddStencilMask(fs2);
            }
        }

        // Save PDF document
        document.Save(dataDir + "AddStencilMasksToImages_out.pdf");
    }
}

منذ 24.4، يمكنك اختيار مصدر الورق حسب حجم صفحة PDF في مربع حوار الطباعة باستخدام واجهة برمجة التطبيقات.

بدءًا من Aspose.PDF 24.4، يمكن تبديل هذا التفضيل باستخدام خاصية Document.PickTrayByPdfSize أو واجهة PdfContentEditor:


private static void PickTrayByPdfSize()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdfFacades_Printing();

    // Create PDF document
    using (var document = new Aspose.Pdf.Document())
    {
        // Add page
        var page = document.Pages.Add();
        page.Paragraphs.Add(new Aspose.Pdf.Text.TextFragment("Hello world!"));

        // Set the flag to choose annotation paper tray using the PDF page size
        document.PickTrayByPdfSize = true;

        // Save PDF document
        document.Save(dataDir + "PickTrayByPdfSize_out.pdf");
    }
}

private static void PickTrayByPdfSizeFacade()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdfFacades_Printing();

    // Create the PdfContentEditor facade
    using (var contentEditor = new Aspose.Pdf.Facades.PdfContentEditor())
    {
        // Bind PDF document
        contentEditor.BindPdf(dataDir + "PrintDocument.pdf");

        // Set the flag to choose annotation paper tray using the PDF page size
        contentEditor.ChangeViewerPreference(Aspose.Pdf.Facades.ViewerPreference.PickTrayByPDFSize);

        // Save PDF document
        contentEditor.Save(dataDir + "PickTrayByPdfSizeFacade_out.pdf");
    }
}

من هذا الإصدار، تمت إضافة ملحق Aspose.PDF Signature لـ .NET:

  • مثال مع إنشاء حقل جديد وخيارات:

// create Signature
var plugin = new Signature();
// create SignOptions object to set instructions
var opt = new SignOptions(inputPfxPath, inputPfxPassword);
// add input file path
opt.AddInput(new FileDataSource(inputPath));
// set output file path
opt.AddOutput(new FileDataSource(outputPath));
// set extra options
opt.Reason = "my Reason";
opt.Contact = "my Contact";
opt.Location = "my Location";
// perform the process
plugin.Process(opt);
  • مثال مع حقل فارغ موجود:

// create Signature
var plugin = new Signature();
// create SignOptions object to set instructions
var opt = new SignOptions(inputPfxPath, inputPfxPassword);
// add input file path with empty signature field
opt.AddInput(new FileDataSource(inputPath));
// set output file path
opt.AddOutput(new FileDataSource(outputPath));
// set name of existing signature field
opt.Name = "Signature1";
// perform the process
plugin.Process(opt);

ما الجديد في Aspose.PDF 24.3

من هذا الإصدار، تمت إضافة ملحق PDF/A Converter لـ .NET:


var options = new PdfAConvertOptions
{
    PdfAVersion = PdfAStandardVersion.PDF_A_3B
};

// Add the source file
options.AddInput(new FileDataSource("path_to_your_pdf_file.pdf")); // replace with your actual file path

// Add the path to save the converted file
options.AddOutput(new FileDataSource("path_to_the_converted_file.pdf"));

// Create the plugin instance
var plugin = new PdfAConverter();

// Run the conversion
plugin.Process(options);
  • تنفيذ بحث عبر قائمة من العبارات في TextFragmentAbsorber:

private static void SearchMultipleRegex()
{
    // Create regular expressions
    var regexes = new Regex[]
    {
        new Regex(@"(?s)document\s+(?:(?:no\(?s?\)?\.?)|(?:number(?:\(?s\)?)?))\s+(?:(?:[\w-]*\d[\w-]*)+(?:[,;\s]|and)*)", RegexOptions.IgnoreCase),
        new Regex(@"[\s\r\n]+Tract[\s\r\n]+of:? ", RegexOptions.IgnoreCase),
        new Regex(@"vested[\s\r\n]+in", RegexOptions.IgnoreCase),
        new Regex("Vested in:", RegexOptions.IgnoreCase),
        new Regex(@"file.?[\s\r\n]+(?:nos?|numbers?|#s?|nums?).?[\s\r\n]+(\d+)-(\d+)", RegexOptions.IgnoreCase),
        new Regex(@"file.?[\s\r\n]+nos?.?:?[\s\r\n]+([\d\r\n-]+)", RegexOptions.IgnoreCase)
    };

    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Text();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "SearchRegularExpressionAll.pdf"))
    {
        // Create TextAbsorber object to find all instances of the input search phrase
        var absorber = new Aspose.Pdf.Text.TextFragmentAbsorber(regexes, new Aspose.Pdf.Text.TextSearchOptions(true));
        document.Pages.Accept(absorber);
        // Get result
        var result = absorber.RegexResults;
    }
}

منذ 24.3، أصبح من الممكن إضافة حقل توقيع فارغ على كل صفحة إلى ملف PDF/A.


private static void AddEmptySignatureFieldOnEveryPage()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
    var fieldName = "signature_1234";

    using (var document = new Aspose.Pdf.Document(dataDir + "PDFAToPDF.pdf"))
    {
        // The new suggested code, using SignatureField object
        var signatureField = new Aspose.Pdf.Forms.SignatureField(document.Pages[1], new Aspose.Pdf.Rectangle(10, 10, 100, 100));

        // Add the default appearance for the signature field
        signatureField.DefaultAppearance = new Aspose.Pdf.Annotations.DefaultAppearance("Helv", 12, System.Drawing.Color.Black);
        var newAddedField = document.Form.Add(signatureField, fieldName, 1);

        // Find annotation associated with the field
        Aspose.Pdf.Annotations.Annotation addedAnnotation = null;
        foreach (Aspose.Pdf.Annotations.Annotation annotation in document.Pages[1].Annotations)
        {
            if (annotation.FullName == fieldName)
            {
                addedAnnotation = annotation;
                break;
            }
        }

        // Add the annotation to every page except the initial
        if (addedAnnotation != null)
        {
            for (int p = 2; p <= document.Pages.Count; p++)
            {
                document.Pages[p].Annotations.Add(addedAnnotation);
            }
        }

        // Save PDF document
        document.Save(dataDir + "outputPdfaWithSignatureFields.pdf");
    }
}

ما الجديد في Aspose.PDF 24.2

منذ 24.2، أصبح من الممكن الحصول على بيانات المتجه من ملف PDF.

تم تنفيذ GraphicsAbsorber للحصول على بيانات المتجه من المستندات:


private static void UsingGraphicsAbsorber()
{
    // The path to the document directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Images();

    // Open the document
    using (var document = new Aspose.Pdf.Document(dataDir + "DocumentWithVectorGraphics.pdf"))
    {
        // Create an instance of GraphicsAbsorber
        using (var graphicsAbsorber = new Aspose.Pdf.Vector.GraphicsAbsorber())
        {
            // Select the first page of the document
            var page = document.Pages[1];

            // Use the `Visit` method to extract graphics from the page
            graphicsAbsorber.Visit(page);

            // Display information about the extracted elements
            foreach (var element in graphicsAbsorber.Elements)
            {
                Console.WriteLine($"Page Number: {element.SourcePage.Number}");
                Console.WriteLine($"Position: ({element.Position.X}, {element.Position.Y})");
                Console.WriteLine($"Number of Operators: {element.Operators.Count}");
            }
        }
    }
}

ما الجديد في Aspose.PDF 24.1

منذ إصدار 24.1، أصبح من الممكن استيراد التعليقات التوضيحية بتنسيق FDF إلى PDF:


private static void ImportFDFByForm()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdfFacades_Forms();

    using (var form = new Aspose.Pdf.Facades.Form(dataDir + "input.pdf"))
    {
        // Open FDF file
        using (var fdfInputStream = new FileStream(dataDir + "student.fdf", FileMode.Open))
        {
            form.ImportFdf(fdfInputStream);
        }
        // Save PDF document
        form.Save(dataDir + "ImportDataFromPdf_Form_out.pdf");
    }
}

أيضًا، دعم الوصول إلى قاموس الصفحة أو فهرس المستند.

إليك أمثلة من الشيفرة لـ DictionaryEditor:

  • إضافة قيم جديدة

private static void AddNewKeysToPdfPageDictionary()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();

    // example of key's names
    string KEY_NAME = "name";
    string KEY_STRING = "str";
    string KEY_BOOL = "bool";
    string KEY_NUMBER = "number";

    // Open the document
    using (var document = new Aspose.Pdf.Document())
    {
        var page = document.Pages.Add();
        var dictionaryEditor = new Aspose.Pdf.DataEditor.DictionaryEditor(page);

        dictionaryEditor.Add(KEY_NAME, new Aspose.Pdf.DataEditor.CosPdfName("name data"));
        dictionaryEditor.Add(KEY_STRING, new Aspose.Pdf.DataEditor.CosPdfString("string data"));
        dictionaryEditor.Add(KEY_BOOL, new Aspose.Pdf.DataEditor.CosPdfBoolean(true));
        dictionaryEditor.Add(KEY_NUMBER, new Aspose.Pdf.DataEditor.CosPdfNumber(11.2));

        // Save PDF document
        document.Save(dataDir + "PageDictionaryEditor_out.pdf");
    }
}
  • إضافة وتعيين قيم إلى القاموس

private static void ModifyKeysInPdfPageDictionary()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();

    string KEY_NAME = "name";

    // Open the document
    using (var document = new Aspose.Pdf.Document())
    {
        var page = document.Pages.Add();
        var dictionaryEditor = new Aspose.Pdf.DataEditor.DictionaryEditor(page);
        dictionaryEditor.Add(KEY_NAME, new Aspose.Pdf.DataEditor.CosPdfName("Old data"));
        // Modify existing value
        dictionaryEditor[KEY_NAME] = new Aspose.Pdf.DataEditor.CosPdfName("New data");

        // Save PDF document
        document.Save(dataDir + "PageDictionaryEditorEdit_out.pdf");
    }
}
  • الحصول على قيمة من القاموس

private static void GetValuesFromPdfPageDictionary()
{
    string KEY_NAME = "name";

    using (var document = new Aspose.Pdf.Document())
    {
        var page = document.Pages.Add();
        var dictionaryEditor = new Aspose.Pdf.DataEditor.DictionaryEditor(page);
        dictionaryEditor[KEY_NAME] = new Aspose.Pdf.DataEditor.CosPdfName("name");
        var value = dictionaryEditor[KEY_NAME];
        // or 
        Aspose.Pdf.DataEditor.ICosPdfPrimitive primitive;
        dictionaryEditor.TryGetValue(KEY_NAME, out primitive);
    }
}
  • إزالة قيمة من القاموس

private static void RemoveFromPdfPageDictionary()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();

    string KEY_NAME = "name";
    string EXPECTED_NAME = "name data";

    using (var document = new Aspose.Pdf.Document())
    {
        var page = document.Pages.Add();
        var dictionaryEditor = new Aspose.Pdf.DataEditor.DictionaryEditor(page);
        dictionaryEditor.Add(KEY_NAME, new Aspose.Pdf.DataEditor.CosPdfName(EXPECTED_NAME));
        dictionaryEditor.Remove(KEY_NAME);

        // Save PDF document
        document.Save(dataDir + "PageDictionaryEditorRemove_out.pdf");
    }
}