コード例 #1
0
        private void btnImport_Click(object sender, System.EventArgs e)
        {
            PdfLoadedDocument lDoc = new PdfLoadedDocument(txtUrl.Tag.ToString());
            PdfFont           font = new PdfStandardFont(PdfFontFamily.Helvetica, 36f);

            foreach (PdfPageBase lPage in lDoc.Pages)
            {
                PdfGraphics      g     = lPage.Graphics;
                PdfGraphicsState state = g.Save();
                g.SetTransparency(0.25f);
                g.RotateTransform(-40);
                g.DrawString(txtStamp.Text, font, PdfPens.Red, PdfBrushes.Red, new PointF(-150, 450));
                g.Restore(state);

                if (chbWatermark.Checked)
                {
                    g.Save();
                    PdfImage image = new PdfBitmap(@"..\..\..\..\..\..\..\Common\Images\PDF\Ani.gif");
                    g.SetTransparency(0.25f);
                    g.DrawImage(image, 0, 0, lPage.Graphics.ClientSize.Width, lPage.Graphics.ClientSize.Height);
                    g.Restore();
                }
            }


            lDoc.Save("Sample.pdf");

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
                System.Diagnostics.Process.Start("Sample.pdf");
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
コード例 #2
0
        public ActionResult ImportAndStamp(string Browser, string Stamptext, IFormFile file)
        {
            PdfLoadedDocument ldoc = null;

            if (file != null && file.Length > 0)
            {
                ldoc = new PdfLoadedDocument(file.OpenReadStream());

                PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 36f);

                foreach (PdfPageBase lPage in ldoc.Pages)
                {
                    PdfGraphics      graphics = lPage.Graphics;
                    PdfGraphicsState state    = graphics.Save();
                    graphics.SetTransparency(0.25f);
                    graphics.RotateTransform(-40);
                    graphics.DrawString(Stamptext, font, PdfPens.Red, PdfBrushes.Red, new PointF(-150, 450));
                    graphics.Restore(state);
                }
            }
            else
            {
                ViewBag.lab = "NOTE: Please select PDF document.";
                return(View());
            }

            MemoryStream stream = new MemoryStream();

            //Save the PDF document
            ldoc.Save(stream);

            stream.Position = 0;

            //Close the PDF document
            ldoc.Close(true);

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");

            fileStreamResult.FileDownloadName = "Stamp.pdf";
            return(fileStreamResult);
        }
コード例 #3
0
ファイル: Stamping.xaml.cs プロジェクト: chinochuy/Xamarin
        void OnButtonClicked(object sender, EventArgs e)
        {
            //Load PDF document to stream.
            Stream docStream = typeof(Stamping).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Product Catalog.pdf");

            //Load the PDF document into the loaded document object.
            PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream);

            //Create font object.
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular);

            //Stamp or watermark on all the pages.
            foreach (PdfPageBase lPage in ldoc.Pages)
            {
                PdfGraphics      g     = lPage.Graphics;
                PdfGraphicsState state = g.Save();
                g.TranslateTransform(ldoc.Pages[0].Size.Width / 2, ldoc.Pages[0].Size.Height / 2);
                g.SetTransparency(0.25f);
                SizeF waterMarkSize = font.MeasureString("Sample");
                g.RotateTransform(-40);
                g.DrawString("Sample", font, PdfPens.Red, PdfBrushes.Red, new PointF(-waterMarkSize.Width / 2, -waterMarkSize.Height / 2));
                g.Restore(state);
            }
            MemoryStream stream = new MemoryStream();

            //Save the PDF document
            ldoc.Save(stream);

            //Close the document
            ldoc.Close(true);

            //Open in default system viewer.
            if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("Stamping.pdf", "application/pdf", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("Stamping.pdf", "application/pdf", stream);
            }
        }
コード例 #4
0
ファイル: Watermark.cs プロジェクト: afanzcbas/BNFRepo
        public void AddWatermark(string text, string fileName, string resultFileName)
        {
            using (PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor())
            {
                string          fontName     = "Arial Black";
                int             fontSize     = 12;
                PdfStringFormat stringFormat = PdfStringFormat.GenericTypographic;
                stringFormat.Alignment     = PdfStringAlignment.Center;
                stringFormat.LineAlignment = PdfStringAlignment.Center;
                documentProcessor.LoadDocument(fileName);
                using (SolidBrush brush = new SolidBrush(Color.FromArgb(63, Color.Black)))
                {
                    using (Font font = new Font(fontName, fontSize))
                    {
                        foreach (var page in documentProcessor.Document.Pages)
                        {
                            var watermarkSize = page.CropBox.Width * 0.75;
                            using (PdfGraphics graphics = documentProcessor.CreateGraphics())
                            {
                                SizeF  stringSize = graphics.MeasureString(text, font);
                                Single scale      = Convert.ToSingle(watermarkSize / stringSize.Width);
                                graphics.TranslateTransform(Convert.ToSingle(page.CropBox.Width * 0.5), Convert.ToSingle(page.CropBox.Height * 0.5));
                                graphics.RotateTransform(-45);
                                graphics.TranslateTransform(Convert.ToSingle(-stringSize.Width * scale * 0.5), Convert.ToSingle(-stringSize.Height * scale * 0.5));
                                using (Font actualFont = new Font(fontName, fontSize * scale))
                                {
                                    RectangleF rect = new RectangleF(0, 0, stringSize.Width * scale, stringSize.Height * scale);
                                    graphics.DrawString(text, actualFont, brush, rect, stringFormat);
                                }

                                graphics.AddToPageForeground(page, 72, 72);
                            }
                        }
                    }
                }

                documentProcessor.SaveDocument(resultFileName);
            }
        }
コード例 #5
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //Get the template PDF file stream from assembly.
            Stream documentStream = typeof(PdfWatermark).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.pdf_succinctly.pdf");
            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);
            //Create a new font instance.
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 36f);

            //Adding a watermark text to all the PDF pages.
            foreach (PdfPageBase loadedPage in loadedDocument.Pages)
            {
                //Get the PDF page graphics.
                PdfGraphics graphics = loadedPage.Graphics;
                //Save the current graphics state.
                PdfGraphicsState state = graphics.Save();
                //Set transparency to add a watermark text.
                graphics.SetTransparency(0.25f);
                //Rotate the graphics to add a watermark text with 40 degree.
                graphics.RotateTransform(-40);
                //Draw a watermark text to PDF page graphics.
                graphics.DrawString(stampText.Text, font, PdfPens.Red, PdfBrushes.Red, new PointF(-150, 450));
                //Restore the graphics state.
                graphics.Restore(state);
            }

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the document into stream.
                loadedDocument.Save(stream);
                loadedDocument.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("PdfWatermark.pdf", stream);
            }
        }
コード例 #6
0
        private void GenerateReportOfSegment(double BegMeasure, double endMeasure, string outFile)
        {
            if (checkBoxRotateMap.Checked)
            {
                IFeatureLayer pCenterlineLayer    = null;
                string        pCenterlineFileName = comboBoxExCenterline.SelectedItem.ToString();
                for (int i = 0; i < pMapcontrol.LayerCount; i++)
                {
                    if (pCenterlineFileName == pMapcontrol.get_Layer(i).Name)
                    {
                        pCenterlineLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                    }
                }
                IFeatureClass pCenterlineFC = pCenterlineLayer.FeatureClass;
                try
                {
                    IFeatureCursor pCurcor  = pCenterlineFC.Search(null, false);
                    IFeature       pFeature = pCurcor.NextFeature();
                    IGeometry      pGeo     = pFeature.Shape;
                    IMSegmentation pMS      = pGeo as IMSegmentation;
                    double         minM     = pMS.MMin;
                    double         maxM     = pMS.MMax;
                    BegMeasure = BegMeasure < minM ? minM : BegMeasure;
                    endMeasure = endMeasure > maxM ? maxM : endMeasure;
                    IPoint begPt = pMS.GetPointsAtM(BegMeasure, 0).Geometry[0] as IPoint;
                    IPoint endPt = pMS.GetPointsAtM(endMeasure, 0).Geometry[0] as IPoint;

                    ISpatialReference sourcePrj;
                    sourcePrj = pCenterlineFC.Fields.get_Field(pCenterlineFC.FindField(pCenterlineFC.ShapeFieldName)).GeometryDef.SpatialReference;
                    ISpatialReference targetPrj = pMapcontrol.Map.SpatialReference;
                    IPoint            begPtPrj;
                    IPoint            endPtPrj;
                    begPt.Project(targetPrj);
                    endPt.Project(targetPrj);
                    begPtPrj = begPt;
                    endPtPrj = endPt;
                    IActiveView pView = this.pMapcontrol.Map as IActiveView;
                    pView.ScreenDisplay.DisplayTransformation.Rotation = 0;
                    double widthHeightR = (((double)pView.ExportFrame.right - pView.ExportFrame.left) / ((double)pView.ExportFrame.bottom - pView.ExportFrame.top));
                    // Dim fw As New FileWindow(begPt, endPt, widthHeightR)
                    MCenterlineUtil fw = new MCenterlineUtil(begPtPrj, endPtPrj, widthHeightR);

                    fw.FitActiveViewTo(pView, true);

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pCurcor);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }


            #region //导出arcmap 地图 export mapfram

            IPageLayout _PageLayout = this.pPageLayoutControl.PageLayout;
            SizeF       m_PageSize  = new SizeF();
            double      width;
            double      hight;



            _PageLayout.Page.QuerySize(out width, out hight);
            m_PageSize.Width  = Convert.ToSingle(width);
            m_PageSize.Height = Convert.ToSingle(hight);
            IUnitConverter pUConvert = new UnitConverterClass();
            esriUnits      ut        = _PageLayout.Page.Units;
            float          pageUnitToInchUnitScale = (float)pUConvert.ConvertUnits(1, ut, esriUnits.esriInches);



            var layerOutPageSize = m_PageSize;
            var outputDPI        = 300;
            int BandHeadWidth    = 40;

            var originalActiveView = _PageLayout as IActiveView;
            var activeView         = _PageLayout as IActiveView;
            originalActiveView.Refresh();
            var avEvents = _PageLayout as IActiveViewEvents;

            float centerX = layerOutPageSize.Width / 2;
            float centerY = layerOutPageSize.Height / 2;

            var backGroundEnv = new Envelope() as IEnvelope;
            backGroundEnv.PutCoords(0, 0, layerOutPageSize.Width, layerOutPageSize.Height);

            activeView.Extent = backGroundEnv;
            //System.Threading.Thread.Sleep(2000);

            IExport pExporter = new ExportPDF() as IExport;
            pExporter.ExportFileName = outFile;
            pExporter.Resolution     = outputDPI;

            var pExPdf = pExporter as IExportPDF;
            pExPdf.Compressed       = true;
            pExPdf.ImageCompression = esriExportImageCompression.esriExportImageCompressionDeflate;

            var screenResolution = GetCurrentScreenResolution();
            var outputResolution = outputDPI;

            ESRI.ArcGIS.esriSystem.tagRECT exportRECT;
            exportRECT.left   = 0;
            exportRECT.top    = 0;
            exportRECT.right  = (int)(activeView.ExportFrame.right * outputResolution / screenResolution) + 1;
            exportRECT.bottom = (int)(activeView.ExportFrame.bottom * outputResolution / screenResolution) + 1;

            var envelope = new Envelope() as IEnvelope;
            envelope.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom);
            pExporter.PixelBounds = envelope;

            var hDC = pExporter.StartExporting();
            activeView.Output(hDC, outputDPI, exportRECT, backGroundEnv, null);

            pExporter.FinishExporting();
            pExporter.Cleanup();
            // MessageBox.Show("Export finished.");
            #endregion

            #region  //根据中线图层生成剖面图
            System.Drawing.Point LastBottomLeftPoint = new System.Drawing.Point();
            int         bandwidth = 0;
            PdfGraphics pGraphics = null;

            IFeatureLayer pCenterlinePointLayer = null;
            string        centerlinePointnName  = cboBoxPointLayer.SelectedItem.ToString();

            for (int i = 0; i < pMapcontrol.LayerCount; i++)
            {
                if (centerlinePointnName == pMapcontrol.get_Layer(i).Name)
                {
                    pCenterlinePointLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                }
            }
            IQueryFilter pQF = null;
            DataTable    centerlinePointTable = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pCenterlinePointLayer.FeatureClass as ITable, pQF);
            chartControl1.Series.Clear();
            Series         series  = new Series("高程", ViewType.Line);
            Series         series2 = new Series("埋深", ViewType.Line);
            SecondaryAxisY myAxisY = new SecondaryAxisY("埋深");

            foreach (DataRow r in centerlinePointTable.Rows)
            {
                double m; double z; double underz;
                m = Convert.ToDouble(r[EvConfig.CenterlineMeasureField]);
                if (m < BegMeasure || m > endMeasure)
                {
                    continue;
                }
                if (r[EvConfig.CenterlineMeasureField] != DBNull.Value && r[EvConfig.CenterlineZField] != DBNull.Value)
                {
                    m = Convert.ToDouble(r[EvConfig.CenterlineMeasureField]);
                    z = Convert.ToDouble(r[EvConfig.CenterlineZField]);
                    series.Points.Add(new SeriesPoint(m, z));
                }
                // if (r[EvConfig.CenterlineMeasureField] != DBNull.Value && r["管道埋深("] != DBNull.Value)
                if (r[EvConfig.CenterlineMeasureField] != DBNull.Value && r[EvConfig.CenterlineBuryDepthField] != DBNull.Value)
                {
                    m = Convert.ToDouble(r[EvConfig.CenterlineMeasureField]);
                    z = Convert.ToDouble(r[EvConfig.CenterlineBuryDepthField]);
                    series2.Points.Add(new SeriesPoint(m, z));
                }
            }

            chartControl1.Series.Add(series);
            chartControl1.Series.Add(series2);
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesY.Clear();
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesX.Clear();
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesY.Add(myAxisY);
            ((LineSeriesView)series2.View).AxisY = myAxisY;
            ((LineSeriesView)series.View).AxisY  = ((XYDiagram)chartControl1.Diagram).AxisY;
            series.ChangeView(ViewType.Line);
            ((XYDiagram)chartControl1.Diagram).AxisY.WholeRange.Auto = true;
            myAxisY.WholeRange.Auto = true;
            series2.ChangeView(ViewType.Line);
            myAxisY.Tickmarks.Visible      = true;
            myAxisY.Tickmarks.MinorVisible = false;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.AutoSideMargins  = false;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.SideMarginsValue = 0;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.SetMinMaxValues(BegMeasure, endMeasure);
            series.ArgumentScaleType = ScaleType.Numerical;

            int ProfileMapHight = 8;

            #endregion


            #region export chartcontrol
            IGraphicsContainer pGC = _PageLayout as IGraphicsContainer;
            pGC.Reset();
            IElement pE = pGC.Next();
            while (pE != null)
            {
                if (pE is IMapFrame)
                {
                    // framgeo related to _PageLayout.Page pagesize, 8.5 x 11, inch
                    IEnvelope framgeo    = pE.Geometry.Envelope as IEnvelope;
                    float     defaultDPI = PdfGraphics.DefaultDpi;
                    double    x          = defaultDPI * framgeo.LowerLeft.X * pageUnitToInchUnitScale;
                    double    y          = defaultDPI * (layerOutPageSize.Height - framgeo.LowerLeft.Y) * pageUnitToInchUnitScale + 1;

                    bandwidth = (int)(defaultDPI * (framgeo.Width * pageUnitToInchUnitScale));

                    LastBottomLeftPoint.X = (int)x;
                    LastBottomLeftPoint.Y = (int)y;

                    chartControl1.Size = new System.Drawing.Size((int)(framgeo.Width * pageUnitToInchUnitScale * defaultDPI), (int)(ProfileMapHight * pageUnitToInchUnitScale * defaultDPI));

                    Image  img = null;
                    Bitmap bmp = null;
                    // Create an image of the chart.
                    ImageFormat format = ImageFormat.Png;
                    using (MemoryStream s = new MemoryStream())
                    {
                        chartControl1.ExportToImage(s, format);
                        img = Image.FromStream(s);
                        bmp = new Bitmap(img);
                        bmp.SetResolution(300, 300);
                    }

                    using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
                    {
                        processor.LoadDocument(outFile);
                        PdfDocument  pd     = processor.Document;
                        PdfPage      page   = pd.Pages[0];
                        PdfRectangle pdfrec = page.MediaBox;
                        // RectangleF rf = new RectangleF(0, 0, Convert.ToSingle(pdfrec.Width) * 96 / 72, Convert.ToSingle(pdfrec.Height) * 96 / 72);
                        // Create and draw PDF graphics.
                        using (pGraphics = processor.CreateGraphics())
                        {
                            PdfGraphics graph = pGraphics;

                            Pen defaultPen = new Pen(Color.Black);
                            defaultPen.Width = 1;
                            graph.DrawImage(bmp, new RectangleF((float)x, (float)y, (float)framgeo.Width * pageUnitToInchUnitScale * defaultDPI, (float)ProfileMapHight * pageUnitToInchUnitScale * defaultDPI));

                            // draw map head.
                            RectangleF MapheadRect = new RectangleF((float)(int)(defaultDPI * framgeo.XMin * pageUnitToInchUnitScale - BandHeadWidth),
                                                                    (float)(int)(defaultDPI * (layerOutPageSize.Height - framgeo.UpperLeft.Y) * pageUnitToInchUnitScale),
                                                                    (float)(int)(BandHeadWidth),
                                                                    (float)(int)(defaultDPI * framgeo.Height * pageUnitToInchUnitScale));
                            graph.DrawRectangle(defaultPen, MapheadRect);
                            //draw head text
                            RectangleF      rF  = new RectangleF(0, 0, (float)MapheadRect.Height, (float)BandHeadWidth);
                            PdfStringFormat psf = new PdfStringFormat(PdfStringFormat.GenericDefault);
                            psf.Alignment     = PdfStringAlignment.Center;
                            psf.LineAlignment = PdfStringAlignment.Center;
                            graph.SaveGraphicsState();
                            // head box 的左下角
                            System.Drawing.Font textfont = new System.Drawing.Font("仿宋", 6F);
                            graph.TranslateTransform((float)(MapheadRect.Left), (float)(MapheadRect.Bottom));
                            graph.RotateTransform(270);
                            graph.DrawString("地图", textfont, new SolidBrush(Color.Black), rF, psf);
                            graph.RestoreGraphicsState();


                            // draw chart head
                            RectangleF ChartheadRect = new RectangleF((float)(int)(defaultDPI * framgeo.XMin * pageUnitToInchUnitScale - BandHeadWidth),
                                                                      (float)(int)(defaultDPI * (layerOutPageSize.Height - framgeo.LowerLeft.Y) * pageUnitToInchUnitScale + 1),
                                                                      (float)(int)(BandHeadWidth),
                                                                      (float)(int)(defaultDPI * ProfileMapHight * pageUnitToInchUnitScale));
                            graph.DrawRectangle(defaultPen, ChartheadRect);
                            //draw head text
                            rF = new RectangleF(0, 0, (float)ChartheadRect.Height, (float)BandHeadWidth);
                            graph.SaveGraphicsState();
                            // head box 的左下角
                            graph.TranslateTransform((float)(ChartheadRect.Left), (float)(ChartheadRect.Bottom));
                            graph.RotateTransform(270);
                            graph.DrawString("剖面图", textfont, new SolidBrush(Color.Black), rF, psf);
                            graph.RestoreGraphicsState();


                            LastBottomLeftPoint.Y = (int)ChartheadRect.Bottom;
                            //double beginM = -999; double endM = -999;
                            //GetIMUBeginEndMeasure(ref beginM, ref endM);
                            double beginM = BegMeasure;
                            double endM   = endMeasure;
                            for (int i = 0; i < listBoxDrawBandFields.Items.Count; i++)
                            {
                                string fieldname = listBoxDrawBandFields.Items[i].ToString();
                                band   b         = new band();
                                b.BandName    = fieldname;
                                b.pdfGC       = pGraphics;
                                b.BandWidth   = (int)bandwidth;
                                b.headFont    = labelbiaotou.Font;
                                b.ContentFont = labelNeirong.Font;
                                System.Drawing.Point pt = new System.Drawing.Point();
                                pt.X = LastBottomLeftPoint.X;
                                pt.Y = LastBottomLeftPoint.Y;
                                b.BandTopLeftLocation = pt;

                                b.BeginM = beginM;
                                b.EndM   = endM;
                                //b.bandData = new List<Tuple<double, string>>();
                                //for (int j = 0; j < 6; j++)
                                //{
                                //    double m = j * 500;
                                //    string txt = "异常2";
                                //    Tuple<double, string> t = new Tuple<double, string>(m,txt);
                                //    b.bandData.Add(t);
                                //}
                                b.bandData = GetPDFBandData(fieldname);
                                b.Draw();
                                LastBottomLeftPoint.Y += (int)b.BandHight;
                            }
                            // graph.DrawImage(img, rf);
                            graph.AddToPageForeground(page);
                            // Render a page with graphics.
                            //processor.RenderNewPage(PdfPaperSize.Letter, graph);
                            processor.SaveDocument(outFile);
                        }
                    }
                    break;
                }
                pE = pGC.Next();
            }
            #endregion
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: svcqa1/POCs
        public static void updateEffectiveDate(string strSiteUrl, string strUserId, string strPassword, string strEffectiveListName, string strDcrDocId)
        {
            try
            {
                using (var context = new ClientContext(strSiteUrl))
                {
                    SecureString passWord = new SecureString();
                    foreach (char c in strPassword.ToCharArray())
                    {
                        passWord.AppendChar(c);
                    }
                    context.Credentials = new SharePointOnlineCredentials(strUserId, passWord);
                    // Gets list object using the list Url
                    List      oList     = context.Web.Lists.GetByTitle(strEffectiveListName);
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='CE_DCRDocID'/>" +
                                        "<Value Type='Lookup'>" + strDcrDocId +
                                        "</Value></Eq></Where></Query></View>";
                    ListItemCollection collListItem = oList.GetItems(camlQuery);
                    context.Load(collListItem);
                    context.ExecuteQuery();
                    foreach (ListItem item in collListItem)
                    {
                        var filePath = item["FileRef"];
                        docFileName = (string)item["FileLeafRef"];


                        Microsoft.SharePoint.Client.File file = item.File;
                        docLinkUrl = new Uri(context.Url).GetLeftPart(UriPartial.Authority) + filePath;
                        if (file != null)
                        {
                            //Loading Uploaded file
                            context.Load(file);
                            context.ExecuteQuery();
                            string dskFilePath = System.IO.Path.Combine(@"C:\Srini\Celitotech\Dev\PDF files\", file.Name);
                            using (System.IO.FileStream Local_stream = System.IO.File.Open(dskFilePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite))
                            {
                                var fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, file.ServerRelativeUrl);
                                var Sp_Stream       = fileInformation.Stream;
                                Sp_Stream.CopyTo(Local_stream);
                            }

                            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(dskFilePath);
                            PdfDocument       document       = new PdfDocument();
                            document.ImportPageRange(loadedDocument, 0, loadedDocument.Pages.Count - 1);
                            document.Template.Top    = AddHeader(document, spHeaderLine1, spHeaderLine2, spHeaderLine3, spWaterMark, spExpiryDays);
                            document.Template.Bottom = AddFooter(document, spFooterLine1, spFooterLine2, spFooterLine3);

                            for (int i = 0; i < document.Pages.Count; i++)
                            {
                                PdfPageBase loadedPage = document.Pages[i];
                                PdfGraphics graphics   = loadedPage.Graphics;
                                PdfFont     font       = new PdfStandardFont(PdfFontFamily.Helvetica, 45);

                                //Add watermark text
                                PdfGraphicsState state = graphics.Save();
                                graphics.SetTransparency(0.25f);
                                graphics.RotateTransform(-40);
                                string text = spWaterMark;
                                SizeF  size = font.MeasureString(text);
                                graphics.DrawString(spWaterMark, font, PdfPens.Gray, PdfBrushes.Gray, new PointF(-150, 450));
                            }

                            DateTime            currentTime          = DateTime.Now;
                            Double              dbleExpiryDays       = Convert.ToDouble(spExpiryDays);
                            DateTime            addDaysToCurrentTime = currentTime.AddDays(dbleExpiryDays);
                            PdfJavaScriptAction scriptAction         = new PdfJavaScriptAction("function Expire(){ var currentDate = new Date();  var expireDate = new Date(2021, 3, 8);      if (currentDate < expireDate) {  app.alert(\"This Document has Expired.  You need a new one.\"); this.closeDoc();   }  } Expire(); ");
                            document.Actions.AfterOpen = scriptAction;

                            document.Save(docFileName);
                            document.Close(true);
                            loadedDocument.Close(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #8
0
        private FileStreamResult ExportPDF(List <EOD> edo)
        {
            // Load the PDF Template
            Stream pdfStream = System.IO.File.OpenRead(_hostingEnvironment.WebRootPath + @"\assets\templates\CloseShop2.pdf");

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, (float)8);
            //PdfFont fontText = new PdfStandardFont(PdfFontFamily.Helvetica, (float)12);
            PdfFont fontTextTHSarabunNew = new PdfTrueTypeFont(System.IO.File.OpenRead(_hostingEnvironment.WebRootPath + $@"\assets\fonts\THSarabunNew\THSarabunNew Bold.ttf"), 15);
            PdfFont fontTextCalibri      = new PdfTrueTypeFont(System.IO.File.OpenRead(_hostingEnvironment.WebRootPath + $@"\assets\fonts\calibri\Calibri.ttf"), 13);
            PdfFont fontTextCalibriBold  = new PdfTrueTypeFont(System.IO.File.OpenRead(_hostingEnvironment.WebRootPath + $@"\assets\fonts\calibri\Calibri.ttf"), 13, PdfFontStyle.Bold);

            // Load a PDF document.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(pdfStream);

            //Create a new PDF document.
            PdfDocument pdfDocument = new PdfDocument();

            int     numPage = 1;
            PdfPage pdfPage;

            //Set the format for string.
            PdfStringFormat formatAlignRight  = new PdfStringFormat(PdfTextAlignment.Right);
            PdfStringFormat formatAlignCenter = new PdfStringFormat(PdfTextAlignment.Center);

            edo.ForEach(e => {
                pdfDocument.ImportPage(loadedDocument, 0);

                pdfPage = pdfDocument.Pages[numPage - 1];

                // Create PDF graphics for the page
                PdfGraphics graphics = pdfPage.Graphics;

                float xPosition = 105;
                float yPosition = (float)85.5;//106.5;
                float gap       = (float)20.5;

                #region Header Left
                // Branch Name
                graphics.DrawString(e.BranchName.Replace("KERRY EXPRESS", "Kerry Express"), fontTextTHSarabunNew, PdfBrushes.Black, new PointF(xPosition, yPosition));


                // Date
                yPosition += gap;
                graphics.DrawString(e.Report_Date.ToString("dd-MMMM-yyyy", _cultureTHInfo), fontTextTHSarabunNew, PdfBrushes.Black, new PointF(xPosition, yPosition));


                // Branch ID
                yPosition += gap + (float)1;
                graphics.DrawString(e.BranchID, fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition));


                // Cost Center
                yPosition += gap + (float)1;
                graphics.DrawString(e.ERPID, fontTextTHSarabunNew, PdfBrushes.Black, new PointF(xPosition, yPosition));
                #endregion


                #region Header Right
                // Branch Type
                xPosition = (float)464;
                yPosition = (float)107;
                graphics.DrawString(e.BranchType.Split('-')[0], fontTextCalibri, PdfBrushes.Black, new PointF(xPosition - (float)14.5, yPosition), formatAlignCenter);

                // Total Transfer
                xPosition = (float)555.31;
                yPosition = (float)107;
                graphics.DrawString(e.TotalTransfer.ToString("N"), fontTextCalibriBold, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Shipment
                yPosition += gap;
                graphics.DrawString(e.TotalShipments.ToString("N0"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Boxes
                yPosition += gap;
                graphics.DrawString(e.TotalBoxes.ToString("N0"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);
                #endregion

                #region Detail Service
                xPosition = (float)281.585;
                yPosition = (float)219;
                gap       = (float)19;

                // Transport Service
                graphics.DrawString(e.TransportService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // AM Service
                yPosition += gap - 1;
                graphics.DrawString(e.AMService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // PUP Service
                yPosition += gap - 2;
                graphics.DrawString(e.PUPService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // SAT Service
                yPosition += gap - 1;
                graphics.DrawString(e.SATService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // RAS Service
                yPosition += gap - 1;
                graphics.DrawString(e.RASService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // COD Service
                yPosition += gap - 1;
                graphics.DrawString(e.CODService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // INSUR Service
                yPosition += gap - 1;
                graphics.DrawString(e.INSURService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Package Service
                yPosition += gap - 2;
                graphics.DrawString(e.PACKAGEService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Sale Package Service
                yPosition += gap - 1;
                graphics.DrawString(e.SALEService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);


                // Discount
                yPosition += gap + 1;
                graphics.DrawString(e.Discount.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Line Top-up Service
                yPosition += gap - 1;
                graphics.DrawString(e.LNTUPService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                //rabbitTopUp
                yPosition += gap + 2;
                graphics.DrawString(e.rabbitTopUp.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                //mPayService
                yPosition += gap - 1;
                graphics.DrawString(e.mPayService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total Shipments
                yPosition += gap;
                graphics.DrawString(e.Shipment.ToString("N0"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total Boxes
                yPosition += gap + 2;
                graphics.DrawString(e.Boxes.ToString("N0"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Drop-off Boxes
                yPosition += gap + 2;
                graphics.DrawString(e.DropOffBoxes.ToString("N0"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total Detail Service
                yPosition += (float)34.5;
                graphics.DrawString(e.TotalDetailService.ToString("N"), fontTextCalibriBold, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);
                #endregion

                // Total Freight Revenue
                yPosition += (float)26;
                graphics.DrawString(e.TotalFreightRevenue.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                #region Detail Pay
                xPosition = (float)555.31;
                yPosition = (float)219.5;
                gap       = (float)19;

                // Cash
                graphics.DrawString(e.Cash.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Rabbit
                yPosition += gap + 2;
                graphics.DrawString(e.Rabbit.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Credit Card BBL
                yPosition += gap + 2;
                graphics.DrawString(e.CreditBBL.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Credit Card SCB
                yPosition += gap + 2;
                graphics.DrawString(e.CreditSCB.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Credit QR Payment
                yPosition += gap + 2;
                graphics.DrawString(e.QRPay.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // LinePay
                yPosition += gap + 2;
                graphics.DrawString(e.LinePay.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total Detail Pay
                yPosition += (float)32;
                graphics.DrawString(e.TotalDetailPay.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);
                #endregion

                #region Detail Surcharge
                yPosition = (float)439.5;
                gap       = (float)19;

                // Transportation
                graphics.DrawString(e.Transportation.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // VAS Surcharge
                yPosition += gap + 2;
                graphics.DrawString(e.VASSurcharge.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Discount
                yPosition += gap + 2;
                graphics.DrawString(e.Discount.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Vat
                yPosition += gap + 2;
                graphics.DrawString(e.VAT.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total Detail Surcharge
                yPosition += (float)29;
                graphics.DrawString(e.TotalDetailSurcharge.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);
                #endregion

                #region BSD Surcharge
                xPosition = (float)281.585;
                yPosition = (float)632.5;
                gap       = (float)19;

                // CITY
                graphics.DrawString(e.BSDCity.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // CITYN
                yPosition += gap + 2;
                graphics.DrawString(e.BSDCityn.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // CITYS
                yPosition += gap + 2;
                graphics.DrawString(e.BSDCitys.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Grab
                yPosition += gap + 2;
                graphics.DrawString(e.BSDGrab.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Discount
                yPosition += gap + 2;
                graphics.DrawString(e.BSDDiscount.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total
                yPosition += gap + (float)12.5;
                graphics.DrawString(e.BSDTotalDetailService.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total Consignment
                yPosition += gap + 12;
                graphics.DrawString(e.BSDConsignment.ToString("N0"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);
                #endregion

                #region BSD Surcharge
                xPosition = (float)555.31;
                yPosition = (float)632.5;
                gap       = (float)19;

                // Cash
                graphics.DrawString(e.BSDCash.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Line Pay
                yPosition += gap + 2;
                graphics.DrawString(e.BSDLinePay.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total Payment
                yPosition += gap + 2;
                graphics.DrawString(e.BSDTotalPayment.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Line Topup
                yPosition += gap + 2;
                graphics.DrawString(e.BSDLineTopUp.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Dummy
                yPosition += gap + 2;
                graphics.DrawString("", fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total Payment Cash
                yPosition += gap + (float)12.5;
                graphics.DrawString(e.BSDTotalPaymentCash.ToString("N"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Total Payment Boxes
                yPosition += gap + 12;
                graphics.DrawString(e.BSDBoxes.ToString("N0"), fontTextCalibri, PdfBrushes.Black, new PointF(xPosition, yPosition), formatAlignRight);

                // Lasted Update
                string closedDate = e.LastedUpdate.HasValue
                ? e.LastedUpdate.Value.ToString("dd MMM yyyy HH:mm:ss", _cultureENInfo)
                : "N/A";

                yPosition += gap + (float)7.8;
                xPosition  = pdfDocument.Pages[0].GetClientSize().Width - 24;
                graphics.DrawString($"Closed Date/Time : {closedDate}", font, PdfBrushes.Red, new PointF(xPosition, yPosition), formatAlignRight);
                #endregion


                if (!(e.TotalDetailService.Equals(e.TotalDetailPay) && e.TotalDetailSurcharge.Equals(e.TotalDetailPay)))
                {
                    //watermark text.
                    PdfFont fontTextTHSarabunNewBold = new PdfTrueTypeFont(System.IO.File.OpenRead(_hostingEnvironment.WebRootPath + $@"\assets\fonts\THSarabunNew\THSarabunNew Bold.ttf"), 48);
                    PdfGraphicsState state           = graphics.Save();
                    graphics.SetTransparency(0.50f);
                    graphics.RotateTransform(-40);
                    graphics.DrawString("ข้อมูลไม่ถูกต้อง โปรดติดต่อผู้ดูแลระบบ", fontTextTHSarabunNewBold, PdfPens.Red, PdfBrushes.Red, new PointF(-300, 460));
                }

                numPage++;
            });

            //Set properties to paginate the table.
            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();
            layoutFormat.Break          = PdfLayoutBreakType.FitElement;
            layoutFormat.Layout         = PdfLayoutType.Paginate;
            layoutFormat.PaginateBounds = new RectangleF(20, 20, pdfDocument.Pages[0].GetClientSize().Width - 40, pdfDocument.Pages[0].GetClientSize().Height - 50);

            //Create a Page template that can be used as footer.
            RectangleF             bounds = new RectangleF(0, 0, pdfDocument.Pages[0].GetClientSize().Width, 50);
            PdfPageTemplateElement footer = new PdfPageTemplateElement(bounds);
            PdfBrush brush = new PdfSolidBrush(Color.Black);

            //Create page number field.
            PdfPageNumberField pageNumber = new PdfPageNumberField(font, brush);

            //Create page count field.
            PdfPageCountField count = new PdfPageCountField(font, brush);

            //Add the fields in composite fields.
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumber, count);

            string            printDate          = DateTime.Now.ToString("dd MMM yyyy HH:mm:ss", _cultureENInfo);
            PdfCompositeField compositePrintDate = new PdfCompositeField(font, brush, string.Format("Printed from PDC/CloseShop      Printed Date/Time : {0}", printDate));

            compositeField.Bounds = footer.Bounds;

            //Draw the composite field in footer.
            compositeField.Draw(footer.Graphics, new PointF(pdfDocument.Pages[0].GetClientSize().Width - (float)63.5, 30));
            compositePrintDate.Draw(footer.Graphics, new PointF((float)24, 30));

            //Add the footer template at the bottom.
            pdfDocument.Template.Bottom = footer;

            MemoryStream ms = new MemoryStream();
            pdfDocument.Save(ms);
            ms.Position = 0;

            //Close the document
            pdfDocument.Close(true);

            // Close file
            pdfStream.Dispose();

            //Save the document.
            return(File(ms, "Application/pdf"));
        }