예제 #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Path to folder:\n");
            var pdfPath    = @"E:\Random Applications\PDFMerger\PDFMerger\resources";
            var outputPath = @"E:\Random Applications\PDFMerger\PDFMerger\output";

            var filePaths = Directory.GetDirectories(pdfPath);

            foreach (var path in filePaths)
            {
                var fileNames = Directory.GetFiles(path, "*.pdf", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();

                if (fileNames.Length > 0)
                {
                    PdfDocument outPdf = new PdfDocument();

                    PdfPage frontPage = new PdfPage();
                    outPdf.AddPage(frontPage);

                    int totalPageCount = 2;
                    int verticalOffset = 0;

                    foreach (var file in fileNames)
                    {
                        using (PdfDocument existingPdf = PdfReader.Open($@"{path}\{file}", PdfDocumentOpenMode.Import))
                        {
                            CopyPages(existingPdf, outPdf);

                            XFont     fontNormal = new XFont("Calibri", 20, XFontStyle.Regular);
                            XGraphics gfx        = XGraphics.FromPdfPage(frontPage);
                            var       xrect      = new XRect(240, 395 + verticalOffset, 300, 25);
                            var       rect       = gfx.Transformer.WorldToDefaultPage(xrect);
                            var       pdfrect    = new PdfRectangle(rect);
                            verticalOffset += 30;

                            //file link
                            frontPage.AddDocumentLink(pdfrect, totalPageCount);
                            totalPageCount += existingPdf.Pages.Count;

                            gfx.DrawString(file.Split('.')[0], fontNormal, XBrushes.Black, xrect, XStringFormats.TopLeft);

                            gfx.Dispose();
                        }
                    }

                    var filePathSplit = path.Split('\\');
                    var newFileName   = filePathSplit[filePathSplit.Length - 1];
                    var saveLocation  = $@"{outputPath}\{newFileName}.pdf";
                    outPdf.Save(saveLocation);
                }
            }
        }
예제 #2
0
        static public void UpdateDoc(PdfDocument doc, Dictionary <string, int> url2pagoffset, string pagtitle, int pag0len)
        {
            PdfString uri;

            for (int ipag = 0; ipag < doc.PageCount; ipag++)
            {
                PdfPage outpage = doc.Pages[ipag];

                for (int ianot = 0; ianot < outpage.Annotations.Count; ianot++)
                {
                    PdfAnnotation anot = outpage.Annotations[ianot] as PdfAnnotation;

                    foreach (PdfDictionary dicitem in anot.Elements.Values.OfType <PdfDictionary> ( ))
                    {
                        if ((uri = dicitem.Elements["/URI"] as PdfString) != null)
                        {
                            foreach (string urikey in url2pagoffset.Keys)
                            {
                                Uri    test = null;
                                string urikey2;
                                try
                                {
                                    urikey2 = RemoveEscEtc(urikey);

                                    if (Uri.TryCreate(urikey2, UriKind.Absolute, out test))
                                    {
                                        if (URICompare(uri.Value, urikey2))
                                        {
                                            PdfRectangle rect    = anot.Rectangle as PdfRectangle;
                                            PdfRectangle newrect = rect.Clone( );

                                            int pagnumb = url2pagoffset[urikey] + pag0len;
                                            PdfLinkAnnotation linkanot = outpage.AddDocumentLink(newrect, pagnumb);

                                            linkanot.Title  = pagtitle;
                                            linkanot.Title += " (page " + pagnumb.ToString( ) + ")";

                                            anot.Rectangle = new PdfRectangle(new XRect(0d, 0d, 0d, 0d));
                                        }
                                    }
                                }
                                catch (Exception)
                                { }
                            }
                        }
                    }
                }
            }
        }
예제 #3
0
        private static bool RenderContentPage(PdfPage page, IReadOnlyCollection <Tuple <string, int> > title2page, int frontSize)
        {
            var font = new XFont("Monaco", frontSize, XFontStyle.Bold,
                                 new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always));
            var brush = XBrushes.Black;
            var pen   = new XPen(brush.Color)
            {
                DashStyle = XDashStyle.Dot
            };
            var border = 4;

            using (var g = XGraphics.FromPdfPage(page))
            {
                var maxWidth    = .0;
                var totalHeight = .0;
                var height      = .0;
                foreach (var kv in title2page)
                {
                    var size = g.MeasureString(kv.Item1, font);
                    maxWidth     = Math.Max(size.Width, maxWidth);
                    height       = size.Height;
                    totalHeight += height + border;
                }

                var x = (page.Width.Point - maxWidth) / 2;
                var y = (page.Height.Point - totalHeight) / 2;
                if (x < 0 || y < 0)
                {
                    return(false);
                }

                foreach (var kv in title2page)
                {
                    var rect = new XRect(new XPoint(x, y), new XSize(maxWidth, height));

                    g.DrawString(kv.Item1, font, brush, rect, XStringFormats.TopLeft);
                    g.DrawRectangle(pen, rect);
                    page.AddDocumentLink(new PdfRectangle(g.Transformer.WorldToDefaultPage(rect)), kv.Item2);

                    y += height + border;
                }
            }

            return(true);
        }
        protected void btnCreateSubmittals_Click(object sender, EventArgs e)
        {
            //Page name, Action
            userActivityLog.UserActivityLogs("Dashboard", "Create Document Submittals");

            int    _projectId  = Convert.ToInt32(Session["defaultProject"]);
            string projectName = "Project 1";
            // Create the output document
            PdfDocument outputDocument = new PdfDocument();

            // Show consecutive pages facing. Requires Acrobat 5 or higher.
            outputDocument.PageLayout = PdfPageLayout.SinglePage;

            XFont         font   = new XFont("Verdana", 10, XFontStyle.Bold);
            XStringFormat format = new XStringFormat();

            format.Alignment     = XStringAlignment.Center;
            format.LineAlignment = XLineAlignment.Far;
            XGraphics gfx;
            XRect     box;

            // Create an empty page
            PdfPage page = outputDocument.AddPage();

            // Create a font
            font = new XFont("Verdana", 15, XFontStyle.Bold);
            // Get an XGraphics object for drawing
            gfx = XGraphics.FromPdfPage(page);


            // Create and Save Table of Contents...
            //// Draw the text - Table of Contentd
            gfx.DrawString("TABLE OF CONTENTS ", font, XBrushes.Black,
                           new XRect(100, 60, page.Width, 20),
                           XStringFormats.TopLeft);

            int    positionY  = 90;
            int    indexCount = 2;
            string strSQL     = @"
SELECT * FROM (
SELECT D.Id, P.ProjectName, D.DocumentName, D.DocumentFile, D.Details, 'OwnDoc' as [Type], D.Ordering
            FROM [dbo].[Document] D 
            LEFT JOIN [dbo].[Project] P ON D.ProjectId=P.Id 
            WHERE P.Id=" + _projectId + @"
            AND Ordering!=0
UNION ALL
select S.Id, P.ProjectName, S.DocumentName, s.DocumentFile, S.Details, DR.DocumentType [Type], DR.Ordering
from DocumentRelation DR INNER JOIN [dbo].[Project] P ON DR.ProjectId=P.Id 
INNER JOIN OMSheet S ON S.Id=DR.DocumentId
where DR.ProjectId=" + _projectId + @" AND DR.DocumentType='OMSheet'

UNION ALL
select S.Id, P.ProjectName, S.DocumentName, s.DocumentFile, S.Details, DR.DocumentType [Type], DR.Ordering
from DocumentRelation DR INNER JOIN [dbo].[Project] P ON DR.ProjectId=P.Id 
INNER JOIN SpecSheet S ON S.Id=DR.DocumentId
where DR.ProjectId=" + _projectId + @" AND DR.DocumentType='SpecSheet') A
            ORDER BY Ordering ASC
";
            string filename3  = "";

            dbConnection.Open();
            using (SqlCommand cmd = new SqlCommand(strSQL, dbConnection))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    if (dt.Rows.Count > 0)
                    {
                        projectName = dt.Rows[0]["ProjectName"].ToString();
                        outputDocument.Info.Title = dt.Rows[0]["ProjectName"].ToString();

                        foreach (DataRow row in dt.Rows)
                        {
                            string filex     = row["DocumentName"].ToString() + "        " + indexCount;
                            string filenamex = "";
                            if (row["Type"].ToString() == "OwnDoc")
                            {
                                filenamex = path + "/Uploads/Documents/" + row["DocumentFile"].ToString();
                            }
                            if (row["Type"].ToString() == "OMSheet")
                            {
                                filenamex = path + "/Uploads/OMSheet/" + row["DocumentFile"].ToString();
                            }
                            if (row["Type"].ToString() == "SpecSheet")
                            {
                                filenamex = path + "/Uploads/SpecSheet/" + row["DocumentFile"].ToString();
                            }
                            PdfDocument inputDocumentx = PdfReader.Open(filenamex, PdfDocumentOpenMode.Import);
                            int         count          = inputDocumentx.PageCount;

                            //// Draw the text
                            //gfx.DrawString(filex, font, XBrushes.Black,
                            //  new XRect(0, positionY, page.Width, page.Height),
                            //  XStringFormats.Center);

                            XFont fontNormal = new XFont("Verdana", 15, XFontStyle.Regular);

                            //Set link position
                            var xrect   = new XRect(100, positionY, page.Width, 20);
                            var rect    = gfx.Transformer.WorldToDefaultPage(xrect);
                            var pdfrect = new PdfRectangle(rect);

                            //file link
                            //page.AddFileLink(pdfrect, filename3);
                            //gfx2.DrawString("open file CompareDocument1_tempfile.pdf", fontNormal, XBrushes.Black, xrect, XStringFormats.TopLeft);

                            //Goto  Page 2
                            page.AddDocumentLink(pdfrect, indexCount);
                            gfx.DrawString(filex, fontNormal, XBrushes.Black, xrect, XStringFormats.TopLeft);

                            //TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer c = new TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer();
                            //c.SetHtml("<html><body style='font-size:20px'>Whatever</body></html>");
                            //c.PerformPaint(gfx);

                            positionY  += 20;
                            indexCount += count;
                        }

                        // Create and Save Table of Contents...
                        filename3 = path + "/Uploads/Documents/" + projectName + ".pdf";
                        outputDocument.Save(filename3);
                    }
                }
            }
            //Initial the doc so its starts new
            //Add cover page
            outputDocument = new PdfDocument();
            strSQL         = @"SELECT D.Id, P.ProjectName, D.DocumentName, D.DocumentFile, D.Details 
            FROM [dbo].[Document] D 
            LEFT JOIN [dbo].[Project] P ON D.ProjectId=P.Id 
            WHERE P.Id=" + _projectId + @" 
            AND Ordering=0
            ORDER BY Ordering ASC";

            //dbConnection.Open();
            using (SqlCommand cmd = new SqlCommand(strSQL, dbConnection))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    if (dt.Rows.Count > 0)
                    {
                        projectName = dt.Rows[0]["ProjectName"].ToString();
                        outputDocument.Info.Title = dt.Rows[0]["ProjectName"].ToString();

                        font = new XFont("Verdana", 10, XFontStyle.Bold);
                        foreach (DataRow row in dt.Rows)
                        {
                            string      filex          = row["DocumentFile"].ToString();
                            string      filenamex      = path + "/Uploads/Documents/" + filex;
                            PdfDocument inputDocumentx = PdfReader.Open(filenamex, PdfDocumentOpenMode.Import);
                            int         count2         = inputDocumentx.PageCount;
                            for (int idx = 0; idx < count2; idx++)
                            {
                                // Get page from 1st document
                                PdfPage page1 = inputDocumentx.PageCount > idx ?
                                                inputDocumentx.Pages[idx] : new PdfPage();

                                // Add pages to the output document
                                page1 = outputDocument.AddPage(page1);

                                // Write document file name and page number on each page
                                gfx = XGraphics.FromPdfPage(page1);
                                box = page1.MediaBox.ToXRect();
                                box.Inflate(0, -10);
                            }
                        }

                        //// Save the document...
                        //string filename3 = path + "/Uploads/Documents/" + projectName + ".pdf";
                        //outputDocument.Save(filename3);
                    }
                }
            }

            // Add table content page
            //string filex2 = "Index";
            string      filenamex2      = filename3;
            PdfDocument inputDocumentx2 = PdfReader.Open(filenamex2, PdfDocumentOpenMode.Import);
            int         count22         = inputDocumentx2.PageCount;

            for (int idx = 0; idx < count22; idx++)
            {
                // Get page from 1st document
                PdfPage page1 = inputDocumentx2.PageCount > idx ?
                                inputDocumentx2.Pages[idx] : new PdfPage();

                // Add pages to the output document
                page1 = outputDocument.AddPage(page1);

                // Write document file name and page number on each page
                gfx = XGraphics.FromPdfPage(page1);
                box = page1.MediaBox.ToXRect();
                box.Inflate(0, -10);
            }

            // Add other pages
            int pageNo = 2;

            strSQL = @"
            SELECT * FROM (
            SELECT D.Id, P.ProjectName, D.DocumentName, D.DocumentFile, D.Details, 'OwnDoc' as [Type], D.Ordering
                        FROM [dbo].[Document] D 
                        LEFT JOIN [dbo].[Project] P ON D.ProjectId=P.Id 
                        WHERE P.Id=" + _projectId + @"
                        AND Ordering!=0
            UNION ALL
            select S.Id, P.ProjectName, S.DocumentName, s.DocumentFile, S.Details, DR.DocumentType [Type], DR.Ordering
            from DocumentRelation DR INNER JOIN [dbo].[Project] P ON DR.ProjectId=P.Id 
            INNER JOIN OMSheet S ON S.Id=DR.DocumentId
            where DR.ProjectId=" + _projectId + @" AND DR.DocumentType='OMSheet'

            UNION ALL
            select S.Id, P.ProjectName, S.DocumentName, s.DocumentFile, S.Details, DR.DocumentType [Type], DR.Ordering
            from DocumentRelation DR INNER JOIN [dbo].[Project] P ON DR.ProjectId=P.Id 
            INNER JOIN SpecSheet S ON S.Id=DR.DocumentId
            where DR.ProjectId=" + _projectId + @" AND DR.DocumentType='SpecSheet') A
                        ORDER BY Ordering ASC
            ";
            //dbConnection.Open();
            using (SqlCommand cmd = new SqlCommand(strSQL, dbConnection))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    if (dt.Rows.Count > 0)
                    {
                        projectName = dt.Rows[0]["ProjectName"].ToString();
                        outputDocument.Info.Title = dt.Rows[0]["ProjectName"].ToString();

                        font = new XFont("Verdana", 10, XFontStyle.Bold);
                        foreach (DataRow row in dt.Rows)
                        {
                            string filex     = row["DocumentFile"].ToString();
                            string filenamex = "";
                            //filenamex = path + "/Uploads/Documents/" + filex;
                            if (row["Type"].ToString() == "OwnDoc")
                            {
                                filenamex = path + "/Uploads/Documents/" + row["DocumentFile"].ToString();
                            }
                            if (row["Type"].ToString() == "OMSheet")
                            {
                                filenamex = path + "/Uploads/OMSheet/" + row["DocumentFile"].ToString();
                            }
                            if (row["Type"].ToString() == "SpecSheet")
                            {
                                filenamex = path + "/Uploads/SpecSheet/" + row["DocumentFile"].ToString();
                            }
                            PdfDocument inputDocumentx = PdfReader.Open(filenamex, PdfDocumentOpenMode.Import);
                            int         count2         = inputDocumentx.PageCount;
                            for (int idx = 0; idx < count2; idx++)
                            {
                                // Get page from 1st document
                                PdfPage page1 = inputDocumentx.PageCount > idx ?
                                                inputDocumentx.Pages[idx] : new PdfPage();

                                // Add pages to the output document
                                page1 = outputDocument.AddPage(page1);

                                // Write document file name and page number on each page
                                gfx = XGraphics.FromPdfPage(page1);
                                box = page1.MediaBox.ToXRect();
                                box.Inflate(0, -10);
                                gfx.DrawString(String.Format("{0}  {1}", "Page - ", pageNo),
                                               font, XBrushes.Red, box, format);
                                pageNo += 1;
                            }
                        }
                        dbConnection.Dispose();
                        // Save the document...
                        filename3 = path + "/Uploads/Documents/" + projectName + ".pdf";
                        outputDocument.Save(filename3);

                        Response.ContentType = "Application/pdf";
                        Response.AppendHeader("Content-Disposition", "attachment; filename=" + projectName + ".pdf");
                        Response.TransmitFile(Server.MapPath(@"~/Uploads/Documents/" + projectName + ".pdf"));
                        Response.End();
                    }
                }
            }
        }
        protected void btnCreateSubmittals_Click(object sender, EventArgs e)
        {
            int    _projectId  = Convert.ToInt32(Session["defaultProject"]);
            string projectName = "Project 1";
            // Create the output document
            PdfDocument outputDocument = new PdfDocument();

            // Show consecutive pages facing. Requires Acrobat 5 or higher.
            outputDocument.PageLayout = PdfPageLayout.SinglePage;

            XFont         font   = new XFont("Verdana", 10, XFontStyle.Bold);
            XStringFormat format = new XStringFormat();

            format.Alignment     = XStringAlignment.Center;
            format.LineAlignment = XLineAlignment.Far;
            XGraphics gfx;
            XRect     box;

            // Create an empty page
            PdfPage page = outputDocument.AddPage();

            // Create a font
            font = new XFont("Verdana", 15, XFontStyle.Bold);
            // Get an XGraphics object for drawing
            gfx = XGraphics.FromPdfPage(page);

            //// Draw the text - Table of Contentd
            gfx.DrawString("TABLE OF CONTENTS ", font, XBrushes.Black,
                           new XRect(100, 60, page.Width, 20),
                           XStringFormats.TopLeft);

            int    positionY  = 90;
            int    indexCount = 2;
            int    pageNo     = 2;
            string strSQL     = @"SELECT D.Id, P.ProjectName, D.DocumentName, D.DocumentFile, D.Details 
            FROM [dbo].[Document] D 
            LEFT JOIN [dbo].[Project] P ON D.ProjectId=P.Id 
            WHERE P.Id=" + _projectId + @"
            ORDER BY Ordering ASC";

            dbConnection.Open();
            using (SqlCommand cmd = new SqlCommand(strSQL, dbConnection))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    if (dt.Rows.Count > 0)
                    {
                        outputDocument.Info.Title = dt.Rows[0]["ProjectName"].ToString();;

                        foreach (DataRow row in dt.Rows)
                        {
                            string filex = row["DocumentName"].ToString() + "        " + indexCount;

                            string      filenamex      = path + "/Uploads/Documents/" + row["DocumentFile"].ToString();
                            PdfDocument inputDocumentx = PdfReader.Open(filenamex, PdfDocumentOpenMode.Import);
                            int         count          = inputDocumentx.PageCount;

                            //// Draw the text
                            //gfx.DrawString(filex, font, XBrushes.Black,
                            //  new XRect(0, positionY, page.Width, page.Height),
                            //  XStringFormats.Center);

                            XFont fontNormal = new XFont("Verdana", 15, XFontStyle.Regular);

                            //Set link position
                            var xrect   = new XRect(100, positionY, page.Width, 20);
                            var rect    = gfx.Transformer.WorldToDefaultPage(xrect);
                            var pdfrect = new PdfRectangle(rect);

                            //file link
                            //page.AddFileLink(pdfrect, filename3);
                            //gfx2.DrawString("open file CompareDocument1_tempfile.pdf", fontNormal, XBrushes.Black, xrect, XStringFormats.TopLeft);

                            //Goto  Page 2
                            page.AddDocumentLink(pdfrect, indexCount);
                            gfx.DrawString(filex, fontNormal, XBrushes.Black, xrect, XStringFormats.TopLeft);

                            //TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer c = new TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer();
                            //c.SetHtml("<html><body style='font-size:20px'>Whatever</body></html>");
                            //c.PerformPaint(gfx);

                            positionY  += 20;
                            indexCount += count;
                        }

                        font = new XFont("Verdana", 10, XFontStyle.Bold);
                        foreach (DataRow row in dt.Rows)
                        {
                            string      filex          = row["DocumentFile"].ToString();
                            string      filenamex      = path + "/Uploads/Documents/" + filex;
                            PdfDocument inputDocumentx = PdfReader.Open(filenamex, PdfDocumentOpenMode.Import);
                            int         count2         = inputDocumentx.PageCount;
                            for (int idx = 0; idx < count2; idx++)
                            {
                                // Get page from 1st document
                                PdfPage page1 = inputDocumentx.PageCount > idx ?
                                                inputDocumentx.Pages[idx] : new PdfPage();

                                // Add pages to the output document
                                page1 = outputDocument.AddPage(page1);

                                // Write document file name and page number on each page
                                gfx = XGraphics.FromPdfPage(page1);
                                box = page1.MediaBox.ToXRect();
                                box.Inflate(0, -10);
                                gfx.DrawString(String.Format("{0}  {1}", "Page - ", pageNo),
                                               font, XBrushes.Red, box, format);
                                pageNo += 1;
                            }
                        }

                        // Save the document...
                        string filename3 = path + "/Uploads/Documents/" + projectName + ".pdf";
                        outputDocument.Save(filename3);
                        Process.Start(filename3);
                    }
                }
            }
        }