.NET PDFSHARP 设置pdf 页面大小的代码

时间:2024-02-21 21:37:52

 

  •  

    i am convert a image to pdf using pdfsharp lib. i need to set margin & page size so i got a trick from this forum to set page size and margin. from here i got code which i used but getting error for two area. here is code which i got.

    page = document.AddPage();
    //page.Size = PdfSharp.PageSize.A4;
    XSize size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);
    if(page.Orientation == PageOrientation.Landscape)
    {
       page.Width  = size.Height;
       page.Height = size.Width;
    }
    else
    {
       page.Width  = size.Width;
       page.Height = size.Height;
    }
    
    // default unit in points 1 inch = 72 points
    page.TrimMargins.Top = 5;
    page.TrimMargins.Right = 5;
    page.TrimMargins.Bottom = 5;
    page.TrimMargins.Left = 5;

    i got a error for this line

    XSize size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);

    so i need to change it to

    System.Drawing.Size size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);

    now my program compile but when i set margin then i am getting error called PdfSharp does not contain a definition for TrimMargins

    these below line does not compile for setting margin.

        pdfPage.TrimMargins.Top = 5;
        pdfPage.TrimMargins.Right = 5;
        pdfPage.TrimMargins.Bottom = 5;
        pdfPage.TrimMargins.Left = 5;

    i am using the pdf sharp library version 1.0.898.0

    so guide me how can i set margin.

    here is my full code to generate pdf from image file

    public static string GeneratePdfFromImage(string source)
            {
                string destinaton = source.Replace("gif", "pdf");
                PdfDocument doc = new PdfDocument();
                PdfPage pdfPage = new PdfPage();
                System.Drawing.Size size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);
                pdfPage.Orientation = PageOrientation.Portrait;
    
                pdfPage.Width = size.Width;
                pdfPage.Height = size.Height;
                pdfPage.TrimMargins.Top = 5;
                pdfPage.TrimMargins.Right = 5;
                pdfPage.TrimMargins.Bottom = 5;
                pdfPage.TrimMargins.Left = 5;
    
                doc.Pages.Add(pdfPage);
    
                XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
                XImage img = XImage.FromFile(source);
    
                try
                {
                    xgr.DrawImage(img, 0, 0);
                    doc.Save(destinaton);
                    doc.Close();
                }
                catch (Exception ex)
                {
                    destinaton = "";
                }
    
                return destinaton;
            }
    转载地址:https://social.msdn.microsoft.com/Forums/vstudio/en-US/cc89bebd-ca88-4a23-9f75-be3bf2208a9d/pdfsharp-page-size-and-set-margin-issue-c?forum=csharpgeneral