コード例 #1
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtSaveDir.Text) &&
                !string.IsNullOrEmpty(this.txtProjectName.Text))
            {
                string selectDir = this.txtSaveDir.Text.Trim();
                string projectName = this.txtProjectName.Text.Trim();

                string path = System.IO.Path.Combine(selectDir, this.txtProjectName.Text.Trim());
                System.IO.Directory.CreateDirectory(path);

                DBGlobalService.ProjectFile = System.IO.Path.Combine(path, projectName+".xml");

                //doc.SetSchemaLocation(GlobalService.ConfigXsd);
                if (!System.IO.File.Exists(DBGlobalService.ProjectFile))
                {
                    var stream = System.IO.File.Create(DBGlobalService.ProjectFile);
                    stream.Close();
                }
                var doc = new Document();
                DBGlobalService.CurrentProjectDoc = doc;
                //doc.Load(GlobalService.ProjectFile);
                var prj = doc.CreateNode<ProjectType>();
                doc.Root = prj;
                DBGlobalService.CurrentProject = prj;
                DBGlobalService.CurrentProject.Name = projectName ;

                doc.Save(DBGlobalService.ProjectFile);

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }
コード例 #2
0
ファイル: SceneSerializer.cs プロジェクト: Paltr/SceneEditor
 public static void SaveShapeTemplates(ShapeTemplatesSet templates, string filepath)
 {
   string folder = Directory.GetParent(filepath).FullName;
   Document document = new Document("root");
   DataElement templatesEl = document.RootElement.CreateChild("templates");
   foreach(ShapeTemplate template in templates)
   {
     if(template is CircleTemplate)
     {
       SaveTemplate(templatesEl.CreateChild("circle"), folder, (CircleTemplate)template);
     }
     else if(template is ImageTemplate)
     {
       SaveTemplate(templatesEl.CreateChild("image"), folder, (ImageTemplate)template);
     }
     else if(template is RectTemplate)
     {
       SaveTemplate(templatesEl.CreateChild("rect"), folder, (RectTemplate)template);
     }
     else
     {
       throw new ArgumentException();
     }
   }
   
   document.Save(filepath);
 }
コード例 #3
0
ファイル: DigitalSignature.cs プロジェクト: ParallaxIT/tdb-ws
        private void btnCreatePdf_Click(object sender, EventArgs e)
        {
            // create a PDF document
            Document document = new Document();

            // set the license key
            document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

            // add a page to the PDF document
            PdfPage firstPage = document.AddPage();

            string logoImagePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\img\evologo-250.png");
            string certificateFilePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\certificates\evopdf.pfx");

            PdfFont pdfFont = document.Fonts.Add(new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Point));
            TextElement descriptionTextElement = new TextElement(0, 0,
                "A digital signature was applied on the logo image below. Click on the image to see the signature details", pdfFont);
            AddElementResult addResult = firstPage.AddElement(descriptionTextElement);

            // create the area where the digital signature will be displayed in the PDF document
            // in this sample the area is a logo image but it could be anything else
            ImageElement logoElement = new ImageElement(0, addResult.EndPageBounds.Bottom + 10, 100, logoImagePath);
            addResult = firstPage.AddElement(logoElement);

            //get the #PKCS 12 certificate from file
            DigitalCertificatesCollection certificates = DigitalCertificatesStore.GetCertificates(certificateFilePath, "evopdf");
            DigitalCertificate certificate = certificates[0];

            // create the digital signature over the logo image element
            DigitalSignatureElement signature = new DigitalSignatureElement(addResult.EndPageBounds, certificate);
            signature.Reason = "Protect the document from unwanted changes";
            signature.ContactInfo = "The contact email is [email protected]";
            signature.Location = "Development server";
            firstPage.AddElement(signature);

            string outFilePath = System.IO.Path.Combine(Application.StartupPath, "DigitalSignature.pdf");

            // save the PDF document to disk
            document.Save(outFilePath);

            // close the PDF document to release the resources
            document.Close();

            DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(outFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
コード例 #4
0
        public void SaveToPdfDefault()
        {
            //ExStart
            //ExFor:Document.Save(String)
            //ExSummary:Converts a whole document to PDF using default options.
            Document doc = new Document(MyDir + "Rendering.doc");

            doc.Save(MyDir + @"\Artifacts\Rendering.SaveToPdfDefault.pdf");
            //ExEnd
        }
コード例 #5
0
ファイル: ImageElementDemo.cs プロジェクト: ParallaxIT/tdb-ws
        private void btnCreatePdf_Click(object sender, EventArgs e)
        {
            // create a PDF document
            Document document = new Document();

            // set the license key
            document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

            // add a page to the PDF document
            PdfPage firstPage = document.AddPage();

            string imagesPath = System.IO.Path.Combine(Application.StartupPath, @"..\..\Img");

            // display image in the available space in page and with a auto determined height to keep the aspect ratio
            ImageElement imageElement1 = new ImageElement(0, 0, System.IO.Path.Combine(imagesPath, "evologo-250.png"));
            AddElementResult addResult = firstPage.AddElement(imageElement1);

            // display image with the specified width and the height auto determined to keep the aspect ratio
            // the images is displayed to the right of the previous image and the bounds of the image inside the current page
            // are taken from the AddElementResult object
            ImageElement imageElement2 = new ImageElement(addResult.EndPageBounds.Right + 10, 0, 100,
                    System.IO.Path.Combine(imagesPath, "evologo-250.png"));
            addResult = firstPage.AddElement(imageElement2);

            // Display image with the specified width and the specified height. It is possible for the image to not preserve the aspect ratio
            // The images is displayed to the right of the previous image and the bounds of the image inside the current page
            // are taken from the AddElementResult object
            ImageElement imageElement3 = new ImageElement(addResult.EndPageBounds.Right + 10, 0, 100, 50,
                    System.IO.Path.Combine(imagesPath, "evologo-250.png"));
            addResult = firstPage.AddElement(imageElement3);

            string outFilePath = System.IO.Path.Combine(Application.StartupPath, "ImageElementDemo.pdf");

            // save the PDF document to disk
            document.Save(outFilePath);

            // close the PDF document to release the resources
            document.Close();

            DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(outFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
コード例 #6
0
ファイル: SceneSerializer.cs プロジェクト: Paltr/SceneEditor
 public static void SaveScenes(ScenesSet scenes,
   string filepath, string templatesFilepath)
 {
   Document document = new Document("root");
   DataElement templatesEl = document.RootElement.CreateChild("templates");
   templatesEl.CreateAttribute("filepath", templatesFilepath);
   DataElement scenesContainer = document.RootElement.CreateChild("scenes");
   foreach(Scene scene in scenes)
   {
     DataElement sceneElement = scenesContainer.CreateChild("scene");
     sceneElement.CreateAttribute("name", scene.Name);
     SaveScene(sceneElement, scene);
   }
   
   document.Save(filepath);
 }
コード例 #7
0
        public void SaveToPdfWithOutline()
        {
            //ExStart
            //ExFor:Document.Save(String, SaveOptions)
            //ExFor:PdfSaveOptions
            //ExFor:PdfSaveOptions.HeadingsOutlineLevels
            //ExFor:PdfSaveOptions.ExpandedOutlineLevels
            //ExSummary:Converts a whole document to PDF with three levels in the document outline.
            Document doc = new Document(MyDir + "Rendering.doc");

            PdfSaveOptions options = new PdfSaveOptions();
            options.OutlineOptions.HeadingsOutlineLevels = 3;
            options.OutlineOptions.ExpandedOutlineLevels = 1;

            doc.Save(MyDir + @"\Artifacts\Rendering.SaveToPdfWithOutline.pdf", options);
            //ExEnd
        }
コード例 #8
0
        public void SaveToPdfStreamOnePage()
        {
            //ExStart
            //ExFor:PdfSaveOptions.PageIndex
            //ExFor:PdfSaveOptions.PageCount
            //ExFor:Document.Save(Stream, SaveOptions)
            //ExSummary:Converts just one page (third page in this example) of the document to PDF.
            Document doc = new Document(MyDir + "Rendering.doc");

            using (Stream stream = File.Create(MyDir + @"\Artifacts\Rendering.SaveToPdfStreamOnePage.pdf"))
            {
                PdfSaveOptions options = new PdfSaveOptions();
                options.PageIndex = 2;
                options.PageCount = 1;
                doc.Save(stream, options);
            }
            //ExEnd
        }
コード例 #9
0
ファイル: Form1.cs プロジェクト: NDChen/MyDemoCode
        private void button2_Click(object sender, EventArgs e)
        {
            string path = this.textBox1.Text.Trim();

            if (path != string.Empty)
            {
                label1.Visible = false;

                ThreadPool.QueueUserWorkItem((userState) => {
                    // load PDF document
                    Document pdfDocument = new Document(path);

                    // instantiate Epub Save options
                    EpubSaveOptions options = new EpubSaveOptions();

                    // specify the layout for contents
                    options.ContentRecognitionMode = EpubSaveOptions.RecognitionMode.Flow;

                    // save the ePUB document
                    pdfDocument.Save(path + ".epub", options);

                    if (label1.InvokeRequired)
                    {
                        this.Invoke(new Action(() => { label1.Visible = true; }));
                    }
                    else 
                    {
                        label1.Visible = true;
                    }

                });
            }
            else 
            {
                MessageBox.Show("Please choose a pdf file firstly.");
            }
        }
コード例 #10
0
        private void btnConvert_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            string outFilePath = Path.Combine(Application.StartupPath, "HtmlToPdfElement.pdf");

            // the PDF document
            Document document = null;

            try
            {
                //create a PDF document
                document = new Document();

                // set the license key
                document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

                //optional settings for the PDF document like margins, compression level,
                //security options, viewer preferences, document information, etc
                document.CompressionLevel = PdfCompressionLevel.Normal;
                document.Margins = new Margins(10, 10, 0, 0);
                //document.Security.CanPrint = true;
                //document.Security.UserPassword = "";
                document.DocumentInformation.Author = "HTML to PDF Converter";
                document.ViewerPreferences.HideToolbar = false;

                // set if the JPEG compression is enabled for the images in PDF - default is true
                document.JpegCompressionEnabled = cbJpegCompression.Checked;

                //Add a first page to the document. The next pages will inherit the settings from this page
                PdfPage page = document.Pages.AddNewPage(PdfPageSize.A4, new Margins(10, 10, 0, 0), PdfPageOrientation.Portrait);

                // the code below can be used to create a page with default settings A4, document margins inherited, portrait orientation
                //PdfPage page = document.Pages.AddNewPage();

                // add a font to the document that can be used for the texts elements
                PdfFont font = document.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point));

                // add header and footer before renderng the content
                if (cbAddHeader.Checked)
                    AddHtmlHeader(document);
                if (cbAddFooter.Checked)
                    AddHtmlFooter(document, font);

                // the result of adding an element to a PDF page
                AddElementResult addResult;

                // Get the specified location and size of the rendered content
                // A negative value for width and height means to auto determine
                // The auto determined width is the available width in the PDF page
                // and the auto determined height is the height necessary to render all the content
                float xLocation = float.Parse(textBoxXLocation.Text.Trim());
                float yLocation = float.Parse(textBoxYLocation.Text.Trim());
                float width = float.Parse(textBoxWidth.Text.Trim());
                float height = float.Parse(textBoxHeight.Text.Trim());

                if (radioConvertToSelectablePDF.Checked)
                {
                    // convert HTML to PDF
                    HtmlToPdfElement htmlToPdfElement;

                    // convert a URL to PDF
                    string urlToConvert = textBoxWebPageURL.Text.Trim();

                    htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, urlToConvert);

                    //optional settings for the HTML to PDF converter
                    htmlToPdfElement.FitWidth = cbFitWidth.Checked;
                    htmlToPdfElement.EmbedFonts = cbEmbedFonts.Checked;
                    htmlToPdfElement.LiveUrlsEnabled = cbLiveLinks.Checked;
                    htmlToPdfElement.JavaScriptEnabled = cbScriptsEnabled.Checked;
                    htmlToPdfElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null;

                    // add theHTML to PDF converter element to page
                    addResult = page.AddElement(htmlToPdfElement);
                }
                else
                {
                    HtmlToImageElement htmlToImageElement;

                    // convert HTML to image and add image to PDF document

                    // convert a URL to PDF
                    string urlToConvert = textBoxWebPageURL.Text.Trim();

                    htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, urlToConvert);

                    //optional settings for the HTML to PDF converter
                    htmlToImageElement.FitWidth = cbFitWidth.Checked;
                    htmlToImageElement.LiveUrlsEnabled = cbLiveLinks.Checked;
                    htmlToImageElement.JavaScriptEnabled = cbScriptsEnabled.Checked;
                    htmlToImageElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null;

                    addResult = page.AddElement(htmlToImageElement);
                }

                if (cbAdditionalContent.Checked)
                {
                    // The code below can be used add some other elements right under the conversion result
                    // like texts or another HTML to PDF conversion

                    // add a text element right under the HTML to PDF document
                    PdfPage endPage = document.Pages[addResult.EndPageIndex];
                    TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below there is another HTML to PDF Element", font);
                    nextTextElement.ForeColor = Color.Green;
                    addResult = endPage.AddElement(nextTextElement);

                    // add another HTML to PDF converter element right under the text element
                    endPage = document.Pages[addResult.EndPageIndex];
                    HtmlToPdfElement nextHtmlToPdfElement = new HtmlToPdfElement(0, addResult.EndPageBounds.Bottom + 10, "http://www.google.com");
                    addResult = endPage.AddElement(nextHtmlToPdfElement);
                }

                // save the PDF document to disk
                document.Save(outFilePath);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                // close the PDF document to release the resources
                if (document != null)
                    document.Close();

                this.Cursor = Cursors.Arrow;
            }

            DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(outFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
コード例 #11
0
        private void btnReport_Click(object sender, EventArgs e)
        {
            StudentByBus studentbus = new StudentByBus();
            StudentByBus CurrentStudentbus = new StudentByBus();
            string CurrentBusStopName = "";
            BusSetup bussetup = BusSetupDAO.SelectByBusYearAndRange(this.intSchoolYear.Value, cboBusRange.Text);
            //List<string> newStuNumberList = new List<string>();
            List<string> StudentIDList = K12.Presentation.NLDPanels.Student.SelectedSource;
            List<StudentRecord> stuRec = Student.SelectByIDs(StudentIDList);
            Dictionary<string, StudentByBus> studentbusRecord = new Dictionary<string, StudentByBus>();

            studentbus = StudentByBusDAO.SelectByBusYearAndTimeNameAndStudntID(this.intSchoolYear.Value, this.cboBusRange.Text, StudentIDList[0]);
            if (studentbus != null)
            {
                if (textBusStop.Text != "" && textBusStop.Text != studentbus.BusStopID)
                    studentbus.BusStopID = textBusStop.Text;
                BusStop buses = BusStopDAO.SelectByBusTimeNameAndByStopID(bussetup.BusTimeName, textBusStop.Text);
                CurrentBusStopName = buses.BusStopName;
                int total = 0;
                if (studentbus.DateCount > 0)
                    total = buses.BusMoney * studentbus.DateCount;
                else
                    total = buses.BusMoney * bussetup.DateCount;
                int div_value = total / 10;
                if ((total - div_value * 10) < 5)
                    studentbus.BusMoney = div_value * 10;
                else
                    studentbus.BusMoney = div_value * 10 + 10;
                studentbus.Save();
                CurrentStudentbus = studentbus;
            }
            else
            {
                StudentByBus newstudentbus = new StudentByBus();
                if (textBusStop.Text != "")
                    newstudentbus.BusStopID = textBusStop.Text;
                BusStop buses = BusStopDAO.SelectByBusTimeNameAndByStopID(bussetup.BusTimeName, textBusStop.Text);
                CurrentBusStopName = buses.BusStopName;
                newstudentbus.BusRangeName = cboBusRange.Text;
                newstudentbus.BusStopID = textBusStop.Text;
                newstudentbus.BusTimeName = bussetup.BusTimeName;
                newstudentbus.ClassName = stuRec[0].Class.Name;
                newstudentbus.ClassID = stuRec[0].Class.ID;
                newstudentbus.DateCount = bussetup.DateCount;
                newstudentbus.SchoolYear = bussetup.BusYear;
                newstudentbus.StudentID = stuRec[0].ID;
                int total = buses.BusMoney * bussetup.DateCount;
                int div_value = total / 10;
                if ((total - div_value * 10) < 5)
                    newstudentbus.BusMoney = div_value * 10;
                else
                    newstudentbus.BusMoney = div_value * 10 + 10;
                newstudentbus.Save();

                CurrentStudentbus = newstudentbus;
            }

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版-現有學生.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版-現有學生.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //Document Template = new Document(Application.StartupPath + "\\Customize\\校車繳費單樣版-現有學生.doc");
            Document Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_現有學生));
            //Document Template = new Document();
            //mPreference = TemplatePreference.GetInstance();
            //if (mPreference.UseDefaultTemplate)
            //    Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_新生));
            //else
            //    Template = new Aspose.Words.Document(mPreference.CustomizeTemplate);

            Document doc = new Document();

            Payment SelectPayment = cboPayment.SelectedItem as Payment;

            //新增收費明細。
            List<PaymentDetail> StudentDetails = new List<PaymentDetail>();

            SelectPayment.FillFull();
            List<PaymentDetail> AllStudentdetail = PaymentDetail.GetByTarget("Student", StudentIDList);
            List<PaymentDetail> Studentdetail = new List<PaymentDetail>();
            List<PaymentDetail> CurrentDetails = new List<PaymentDetail>();
            List<PaymentHistory> historys = new List<PaymentHistory>();
            List<string> ids = new List<string>();
            foreach (PaymentDetail var in AllStudentdetail)
            {
                if (var.Extensions["校車收費年度"] != intSchoolYear.Value.ToString() || var.Extensions["校車收費名稱"] != cboBusRange.SelectedItem.ToString())
                    continue;
                Studentdetail.Add(var);
            }

            if (Studentdetail.Count == 0)
            {
                PaymentDetail detail = new PaymentDetail(SelectPayment);    //設定「收費明細」所屬的收費。

                detail.RefTargetID = stuRec[0].ID;//搭乘校車新生ID。
                detail.RefTargetType = "Student";
                detail.Amount = CurrentStudentbus.BusMoney;                  //要收多少錢。
                //detail.Extensions.Add("校車收費年度", intSchoolYear.Value.ToString());
                detail.Extensions.Add("校車收費年度", SelectPayment.SchoolYear.ToString());
                detail.Extensions.Add("校車收費學期", SelectPayment.Semester.ToString());
                detail.Extensions.Add("校車收費名稱", cboBusRange.SelectedItem.ToString());
                detail.Extensions.Add("MergeField::代碼", textBusStop.Text);
                detail.Extensions.Add("MergeField::站名", CurrentBusStopName);
                detail.Extensions.Add("MergeField::" + "學號", stuRec[0].StudentNumber);
                detail.Extensions.Add("MergeField::" + "姓名", stuRec[0].Name);
                detail.Extensions.Add("MergeField::" + "班級", stuRec[0].Class.Name);
                detail.Extensions.Add("開始日期", bussetup.BusStartDate.ToString());
                detail.Extensions.Add("結束日期", bussetup.BusEndDate.ToString());
                detail.Extensions.Add("搭車天數", CurrentStudentbus.DateCount.ToString());
                StudentDetails.Add(detail);                                 //先加到一個 List 中。

                List<string> detailIDs = new List<string>();
                detailIDs = PaymentDetail.Insert(StudentDetails.ToArray());     //新增到資料庫中。

                CurrentDetails = PaymentDetail.GetByIDs(detailIDs.ToArray());

                foreach (PaymentDetail pd in CurrentDetails)
                {
                    MotherForm.SetStatusBarMessage("條碼產生中....");
                    Application.DoEvents();
                    //新增一筆繳費記錄。
                    PaymentHistory history = new PaymentHistory(pd);
                    history.Amount = pd.Amount; //通常會與金額與繳費明細一樣。
                    ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                    historys.Add(history);
                }
                ids = PaymentHistory.Insert(historys);
            }
            else
            {
                foreach (PaymentDetail pdetail in Studentdetail)
                {
                    CurrentDetails.Add(pdetail);
                    if (pdetail.Extensions["校車收費名稱"] == cboBusRange.SelectedItem.ToString() && int.Parse(pdetail.Extensions["校車收費年度"]) == intSchoolYear.Value)
                    {
                        if ((pdetail.Extensions["MergeField::代碼"] != textBusStop.Text && pdetail.Extensions["MergeField::站名"] != CurrentBusStopName) || int.Parse(pdetail.Extensions["搭車天數"]) != CurrentStudentbus.DateCount)
                        {
                            if (CurrentStudentbus.DateCount > 0)
                            {
                                pdetail.Extensions["搭車天數"] = CurrentStudentbus.DateCount.ToString();
                                pdetail.Amount = CurrentStudentbus.BusMoney;
                            }

                            List<PaymentDetail> pdetails = new List<PaymentDetail>();
                            pdetail.Amount = CurrentStudentbus.BusMoney;
                            pdetail.Extensions["MergeField::代碼"] = textBusStop.Text;
                            pdetail.Extensions["MergeField::站名"] = CurrentBusStopName;
                            pdetails.Add(pdetail);
                            PaymentDetail.Update(pdetails.ToArray()); //更新到資料庫中。

                            //註銷先前之繳費單
                            pdetail.CancelExistReceipts();

                            foreach (PaymentDetail pd in CurrentDetails)
                            {
                                MotherForm.SetStatusBarMessage("條碼產生中....");
                                Application.DoEvents();
                                //新增一筆繳費記錄。
                                PaymentHistory history = new PaymentHistory(pd);
                                history.Amount = pd.Amount; //通常會與金額與繳費明細一樣。
                                ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                                historys.Add(history);
                            }
                            ids = PaymentHistory.Insert(historys);
                            continue;
                        }
                        else
                        {
                            pdetail.FillHistories();

                            IList<PaymentHistory> historyss = pdetail.Histories;
                            if (historyss == null)
                                return;
                            foreach (PaymentHistory history in historyss)
                            {
                                if (history.Receipt.Cancelled)
                                    continue;
                                else
                                {
                                    ids.Add(history.UID);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            historys = PaymentHistory.GetByIDs(ids.ToArray());
            //產生繳費單
            ReceiptDocument rdoc = new ReceiptDocument(Template); //如果要自定樣版,可以用這個建構式。
            List<PaymentReceipt> prRecood = new List<PaymentReceipt>();
            foreach (PaymentHistory history in historys)
            {
                MotherForm.SetStatusBarMessage("繳費單產生中....");
                Application.DoEvents();
                prRecood.Add(history.Receipt);
            }
            doc = rdoc.Generate2(prRecood);

            if (doc.Sections.Count != 0)
            {
                string path = Path.Combine(Application.StartupPath, "Reports");
                string reportName = "繳費單";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                path = Path.Combine(path, reportName + ".doc");

                if (File.Exists(path))
                {
                    int i = 1;
                    while (true)
                    {
                        string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                        if (!File.Exists(newPath))
                        {
                            path = newPath;
                            break;
                        }
                    }
                }

                try
                {
                    doc.Save(path, SaveFormat.Doc);
                    System.Diagnostics.Process.Start(path);
                }
                catch
                {
                    System.Windows.Forms.SaveFileDialog sd1 = new System.Windows.Forms.SaveFileDialog();
                    sd1.Title = "另存新檔";
                    sd1.FileName = "繳費單.doc";
                    sd1.Filter = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*";
                    if (sd1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        try
                        {
                            doc.Save(sd1.FileName, SaveFormat.Doc);
                            System.Diagnostics.Process.Start(sd1.FileName);
                        }
                        catch
                        {
                            System.Windows.Forms.MessageBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
            }

            MotherForm.SetStatusBarMessage("繳費單產生完成。");
            this.Close();
        }
コード例 #12
0
ファイル: TextAndFonts.cs プロジェクト: ParallaxIT/tdb-ws
        private void btnCreatePdf_Click(object sender, EventArgs e)
        {
            // create a PDF document
            Document document = new Document();

            // set the license key
            document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

            // add a page to the PDF document
            PdfPage firstPage = document.AddPage();

            // Create a Times New Roman .NET font of 10 points
            System.Drawing.Font ttfFont = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point);
            // Create a Times New Roman Italic .NET font of 10 points
            System.Drawing.Font ttfFontItalic = new System.Drawing.Font("Times New Roman", 10,
                        System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point);
            // Create a Times New Roman Bold .NET font of 10 points
            System.Drawing.Font ttfFontBold = new System.Drawing.Font("Times New Roman", 10,
                        System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point);
            // Create a Times New Roman Bold .NET font of 10 points
            System.Drawing.Font ttfFontBoldItalic = new System.Drawing.Font("Times New Roman", 10,
                        System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point);

            // Create a Sim Sun .NET font of 10 points
            System.Drawing.Font ttfCJKFont = new System.Drawing.Font("SimSun", 10,
                        System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);

            // Create the PDF fonts based on the .NET true type fonts
            PdfFont newTimesFont = document.AddFont(ttfFont);
            PdfFont newTimesFontItalic = document.AddFont(ttfFontItalic);
            PdfFont newTimesFontBold = document.AddFont(ttfFontBold);
            PdfFont newTimesFontBoldItalic = document.AddFont(ttfFontBoldItalic);

            // Create the embedded PDF fonts based on the .NET true type fonts
            PdfFont newTimesEmbeddedFont = document.AddFont(ttfFont, true);
            PdfFont newTimesItalicEmbeddedFont = document.AddFont(ttfFontItalic, true);
            PdfFont newTimesBoldEmbeddedFont = document.AddFont(ttfFontBold, true);
            PdfFont newTimesBoldItalicEmbeddedFont = document.AddFont(ttfFontBoldItalic, true);

            PdfFont cjkEmbeddedFont = document.AddFont(ttfCJKFont, true);

            // Create a standard Times New Roman Type 1 Font
            PdfFont stdTimesFont = document.AddFont(StdFontBaseFamily.TimesRoman);
            PdfFont stdTimesFontItalic = document.AddFont(StdFontBaseFamily.TimesItalic);
            PdfFont stdTimesFontBold = document.AddFont(StdFontBaseFamily.TimesBold);
            PdfFont stdTimesFontBoldItalic = document.AddFont(StdFontBaseFamily.TimesBoldItalic);

            // Create CJK standard Type 1 fonts
            PdfFont cjkJapaneseStandardFont = document.AddFont(StandardCJKFont.HeiseiKakuGothicW5);
            PdfFont cjkChineseTraditionalStandardFont = document.AddFont(StandardCJKFont.MonotypeHeiMedium);

            // Add text elements to the document

            TextElement trueTypeText = new TextElement(0, 10, "True Type Fonts Demo:", newTimesFontBold);
            AddElementResult addResult = firstPage.AddElement(trueTypeText);

            // Create the text element
            TextElement textElement1 = new TextElement(20, addResult.EndPageBounds.Bottom + 10, "Hello World !!!!", newTimesFont);
            // Add element to page. The result of adding the text element is stored into the addResult object
            // which can be used to get information about the rendered size in PDF page.
            addResult = firstPage.AddElement(textElement1);

            // Add another element 5 points below the text above. The bottom of the text above is taken from the AddElementResult object
            // set the font size
            newTimesFontItalic.Size = 15;
            TextElement textElement2 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", newTimesFontItalic);
            textElement2.ForeColor = System.Drawing.Color.Green;
            addResult = firstPage.AddElement(textElement2);

            newTimesFontBoldItalic.Size = 20;
            TextElement textElement3 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", newTimesFontBoldItalic);
            textElement3.ForeColor = System.Drawing.Color.Blue;
            addResult = firstPage.AddElement(textElement3);

            TextElement stdTypeText = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Standard PDF Fonts Demo:", newTimesFontBold);
            addResult = firstPage.AddElement(stdTypeText);

            TextElement textElement4 = new TextElement(20, addResult.EndPageBounds.Bottom + 10, "Hello World !!!!", stdTimesFont);
            addResult = firstPage.AddElement(textElement4);

            stdTimesFontItalic.Size = 15;
            TextElement textElement5 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", stdTimesFontItalic);
            textElement5.ForeColor = System.Drawing.Color.Green;
            addResult = firstPage.AddElement(textElement5);

            stdTimesFontBoldItalic.Size = 20;
            TextElement textElement6 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", stdTimesFontBoldItalic);
            textElement6.ForeColor = System.Drawing.Color.Blue;
            addResult = firstPage.AddElement(textElement6);

            // embedded true type fonts

            TextElement embeddedTtfText = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Embedded True Type Fonts Demo:", newTimesFontBold);
            addResult = firstPage.AddElement(embeddedTtfText);

            // russian text
            TextElement textElement8 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Появление на свет!!", newTimesEmbeddedFont);
            addResult = firstPage.AddElement(textElement8);

            string outFilePath = System.IO.Path.Combine(Application.StartupPath, "TextsAndFontsDemo.pdf");

            // save the PDF document to disk
            document.Save(outFilePath);

            // close the PDF document to release the resources
            document.Close();

            DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(outFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
コード例 #13
0
        public void SetFontsFoldersSystemAndCustomFolder()
        {
            // Store the font sources currently used so we can restore them later.
            FontSourceBase[] origFontSources = FontSettings.GetFontsSources();

            //ExStart
            //ExFor:FontSettings
            //ExFor:FontSettings.GetFontsSources()
            //ExFor:FontSettings.SetFontsSources()
            //ExId:SetFontsFoldersSystemAndCustomFolder
            //ExSummary:Demonstrates how to set Aspose.Words to look for TrueType fonts in system folders as well as a custom defined folder when scanning for fonts.
            Document doc = new Document(MyDir + "Rendering.doc");

            // Retrieve the array of environment-dependent font sources that are searched by default. For example this will contain a "Windows\Fonts\" source on a Windows machines.
            // We add this array to a new ArrayList to make adding or removing font entries much easier.
            ArrayList fontSources = new ArrayList(FontSettings.GetFontsSources());

            // Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
            FolderFontSource folderFontSource = new FolderFontSource("C:\\MyFonts\\", true);

            // Add the custom folder which contains our fonts to the list of existing font sources.
            fontSources.Add(folderFontSource);

            // Convert the Arraylist of source back into a primitive array of FontSource objects.
            FontSourceBase[] updatedFontSources = (FontSourceBase[])fontSources.ToArray(typeof(FontSourceBase));

            // Apply the new set of font sources to use.
            FontSettings.SetFontsSources(updatedFontSources);

            doc.Save(MyDir + "Rendering.SetFontsFolders Out.pdf");
            //ExEnd

            // Verify that font sources are set correctly.
            Assert.IsInstanceOf(typeof(SystemFontSource), FontSettings.GetFontsSources()[0]); // The first source should be a system font source.
            Assert.IsInstanceOf(typeof(FolderFontSource), FontSettings.GetFontsSources()[1]); // The second source should be our folder font source.

            FolderFontSource folderSource = ((FolderFontSource)FontSettings.GetFontsSources()[1]);
            Assert.AreEqual(@"C:\MyFonts\", folderSource.FolderPath);
            Assert.True(folderSource.ScanSubfolders);

            // Restore the original sources used to search for fonts.
            FontSettings.SetFontsSources(origFontSources);
        }
コード例 #14
0
        public void SetTrueTypeFontsFolder()
        {
            // Store the font sources currently used so we can restore them later.
            FontSourceBase[] fontSources = FontSettings.GetFontsSources();

            //ExStart
            //ExFor:FontSettings
            //ExFor:FontSettings.SetFontsFolder(String, Boolean)
            //ExId:SetFontsFolderCustomFolder
            //ExSummary:Demonstrates how to set the folder Aspose.Words uses to look for TrueType fonts during rendering or embedding of fonts.
            Document doc = new Document(MyDir + "Rendering.doc");

            // Note that this setting will override any default font sources that are being searched by default. Now only these folders will be searched for
            // fonts when rendering or embedding fonts. To add an extra font source while keeping system font sources then use both FontSettings.GetFontSources and
            // FontSettings.SetFontSources instead.
            FontSettings.SetFontsFolder(@"C:\MyFonts\", false);

            doc.Save(MyDir + "Rendering.SetFontsFolder Out.pdf");
            //ExEnd

            // Restore the original sources used to search for fonts.
            FontSettings.SetFontsSources(fontSources);
        }
コード例 #15
0
        private void lnkChkMappingField_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Word (*.doc)|*.doc";
            saveDialog.FileName = "綜合表現紀錄表合併欄位說明";
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Document doc = new Document(new MemoryStream(Properties.Resources.綜合表現紀錄表合併欄位說明));
                    doc.Save(saveDialog.FileName);
                }
                catch (Exception ex)
                {
                    FISCA.Presentation.Controls.MsgBox.Show("儲存失敗。" + ex.Message);
                    return;
                }

                try
                {
                    System.Diagnostics.Process.Start(saveDialog.FileName);
                }
                catch (Exception ex)
                {
                    FISCA.Presentation.Controls.MsgBox.Show("開啟失敗。" + ex.Message);
                    return;
                }
            }
        }
コード例 #16
0
        void _bgWork_DoWork(object sender, DoWorkEventArgs e)
        {
            #region 讀取資料並整理
            // 取得所選課程資料
            _CourseAllDict.Clear();
            _StudentDict.Clear();
            _AddressDict.Clear();
            _ParentDict.Clear();

            // 取得學生扣考
            Global._StudentNotExamDict = QueryData.GetStudentNotExamCoID(_StudentIDList);

            // 取得學生資料
            foreach (StudentRecord rec in Student.SelectByIDs(_StudentIDList))
                _StudentDict.Add(rec.ID, rec);

            // 地址資料
            foreach (AddressRecord rec in Address.SelectByStudentIDs(_StudentIDList))
            {
                if (!_AddressDict.ContainsKey(rec.RefStudentID))
                    _AddressDict.Add(rec.RefStudentID, rec);
            }

            // 家長資料
            foreach (ParentRecord rec in K12.Data.Parent.SelectByStudentIDs(_StudentIDList))
            {
                if (!_ParentDict.ContainsKey(rec.RefStudentID))
                    _ParentDict.Add(rec.RefStudentID, rec);
            }

            Dictionary<string, UDTCourseDef> SelCourseDict = UDTTransfer.UDTCourseSelectBySchoolYearSMDict(_SelSchoolYear, _SelSemester, _SelMonth);
            
            _CourseAllDict.Clear();
            foreach (KeyValuePair<string, UDTCourseDef> data in SelCourseDict)
            {
                int cid = int.Parse(data.Key);
                _CourseAllDict.Add(cid, data.Value);
            }
            
            // 取得所選課程上課時間表            
            _TimeSectionList = UDTTransfer.UDTTimeSectionSelectByCourseIDList(SelCourseDict.Keys.ToList());

            _classNameDict.Clear();
            foreach (ClassRecord cr in Class.SelectAll())
                _classNameDict.Add(cr.ID, cr.Name);

            // 取得學生重補修課程缺曠
            _AttendanceList.Clear();
            List<UDTAttendanceDef> StudAddtendList= UDTTransfer.UDTAttendanceSelectByStudentIDList(_StudentIDList);
            foreach (UDTAttendanceDef data in StudAddtendList)
            {
                // 屬於該梯次才加入
                if (_CourseAllDict.ContainsKey(data.CourseID))
                    _AttendanceList.Add(data);
            }

            // 整理學生缺課資料
            Dictionary<string, List<UDTAttendanceDef>> StudAttendanceDict = new Dictionary<string, List<UDTAttendanceDef>>();
            foreach (UDTAttendanceDef data in _AttendanceList)
            { 
                string sid=data.StudentID.ToString();
                if (!StudAttendanceDict.ContainsKey(sid))
                    StudAttendanceDict.Add(sid, new List<UDTAttendanceDef>());

                StudAttendanceDict[sid].Add(data);
            }


            _bgWork.ReportProgress(30);
         
            #endregion

            #region 填值並合併樣板處理

            Document docTemplate=null;
            if(_SelectChkNotExam)
                docTemplate = new Document(new MemoryStream(Properties.Resources.學生重補修缺曠通知單扣考範本));
            else
                docTemplate = new Document(new MemoryStream(Properties.Resources.學生重補修缺曠通知單範本));

            // 最終樣板
            Document doc = new Document();
            // 處理缺曠用
            DataTable dtAtt = new DataTable();
            List<Document> docList = new List<Document>();

            DataTable dt = new DataTable();
            
            List<int> courseIDList = new List<int>();

            string SchoolName = School.ChineseName;
            string SchoolAddress = School.Address;
            string SchoolTel = School.Telephone;

            // 以學生為主產生資料
            foreach(string studID in _StudentIDList)
            {
                // 沒有缺課學生跳過
                if (!StudAttendanceDict.ContainsKey(studID))
                    continue;

                // 檢查當勾選只產生扣考,只顯示有扣考,完全沒扣考跳過
                if (_SelectChkNotExam)
                {
                    if (!Global._StudentNotExamDict.ContainsKey(studID))
                        continue;
                }

                courseIDList.Clear();
                // 學生修課課程
                List<UDTAttendanceDef> sadList = StudAttendanceDict[studID];
                foreach (UDTAttendanceDef data in sadList)
                {
                    if (!courseIDList.Contains(data.CourseID))
                        courseIDList.Add(data.CourseID);
                }


                dt.Clear();
                dt.Columns.Clear();
                // 放入欄位
                dt.Columns.Add("學校名稱");
                dt.Columns.Add("學校地址");
                dt.Columns.Add("學校電話");
                dt.Columns.Add("收件人姓名");
                dt.Columns.Add("收件人地址");
                dt.Columns.Add("學年度");
                dt.Columns.Add("學期");
                dt.Columns.Add("梯次");
                dt.Columns.Add("班級");
                dt.Columns.Add("座號");
                dt.Columns.Add("學號");
                dt.Columns.Add("學生姓名");                

                // 課程名稱
                for (int i = 1; i <= 6; i++)
                {
                    dt.Columns.Add("課程名稱" + i);
                    dt.Columns.Add("缺曠紀錄" + i);
                    dt.Columns.Add("小計" + i);
                    dt.Columns.Add("扣考" + i);
                }

                DataRow dr = dt.NewRow();
                // 學校名稱
                dr["學校名稱"] = SchoolName;
                // 學校地址
                dr["學校地址"] = SchoolAddress;
                // 學校電話
                dr["學校電話"] = SchoolTel;

                // 收件人姓名
                dr["收件人姓名"] = _StudentDict[studID].Name;
                    
                if (_ParentDict.ContainsKey(studID))
                {
                    string name = _StudentDict[studID].Name;
                    if (_SelectMailName == "監護人姓名")
                        name = _ParentDict[studID].CustodianName;

                    if (_SelectMailName == "父親姓名")
                        name = _ParentDict[studID].FatherName;

                    if (_SelectMailName == "母親姓名")
                        name = _ParentDict[studID].MotherName;

                    dr["收件人姓名"] = name;
                        
                }

                // 收件人地址
                dr["收件人地址"] = "";
                if (_AddressDict.ContainsKey(studID))
                {
                    string address = "";
                    if (_SelectMailAddress == "戶籍地址")
                        address = _AddressDict[studID].PermanentAddress;

                    if (_SelectMailAddress == "聯絡地址")
                        address = _AddressDict[studID].MailingAddress;

                    if (_SelectMailAddress == "其他地址")
                        address = _AddressDict[studID].Address1Address;

                    dr["收件人地址"] = address;
                }

                // 班級
                if (_classNameDict.ContainsKey(_StudentDict[studID].RefClassID))
                {
                    dr["班級"] = _classNameDict[_StudentDict[studID].RefClassID];                    
                }

                dr["座號"] = "";
                // 座號
                if (_StudentDict[studID].SeatNo.HasValue)
                    dr["座號"] = _StudentDict[studID].SeatNo.Value;                

                // 學號
                dr["學號"] = _StudentDict[studID].StudentNumber;                

                // 學生姓名
                dr["學生姓名"] = _StudentDict[studID].Name;

                // 清空與重設相關需要資料
                Global._CourseTimeSectionList.Clear();
                Global._CousreAttendList.Clear();
                Global._CourseStudentAttendanceIdxDict.Clear();

                dtAtt.Clear();
                dtAtt.Columns.Clear();
                dtAtt.Columns.Add("缺曠日期");
                // 缺曠資料
                for (int i = 1; i <= 100; i++)
                    dtAtt.Columns.Add("缺曠紀錄" + i);

                DataRow drTT = dtAtt.NewRow();
                // 填入課程名稱
                int coIdx = 1;
                // 收集學年度學期
                List<int> syL = new List<int>();
                List<int> ssL = new List<int>();
                List<int> smL = new List<int>();


                foreach (int cid in courseIDList)
                {
                    if (_CourseAllDict.ContainsKey(cid))
                    {
                        // 勾選只產生扣考,沒有扣考不顯示出來
                        if (_SelectChkNotExam)
                        {
                            if (!Global._StudentNotExamDict.ContainsKey(studID))
                                continue;
                            else
                            {
                                if (!Global._StudentNotExamDict[studID].Contains(cid))
                                    continue;
                            }
                        }
                        dr["課程名稱" + coIdx] = _CourseAllDict[cid].CourseName;

                        if (!syL.Contains(_CourseAllDict[cid].SchoolYear))
                            syL.Add(_CourseAllDict[cid].SchoolYear);

                        if (!ssL.Contains(_CourseAllDict[cid].Semester))
                            ssL.Add(_CourseAllDict[cid].Semester);

                        if (!smL.Contains(_CourseAllDict[cid].Month))
                            smL.Add(_CourseAllDict[cid].Month);


                        int SumCount = 0;

                        // 整理課程上課時間表
                        foreach (UDTTimeSectionDef data in _TimeSectionList)
                        {
                            if (data.CourseID == cid)
                                Global._CourseTimeSectionList.Add(data);
                        }

                        // 整理課程修課缺曠記錄
                        foreach (UDTAttendanceDef data in StudAttendanceDict[studID])
                        {
                            if (data.CourseID == cid)
                            {
                                Global._CousreAttendList.Add(data);
                                SumCount++;
                            }
                        }

                        // 計算學生缺曠統計
                        dr["小計" + coIdx] = SumCount;

                        // 扣考
                        if (Global._StudentNotExamDict.ContainsKey(studID))
                        {
                            if (Global._StudentNotExamDict[studID].Contains(cid))
                                dr["扣考" + coIdx] = "扣考";
                        }

                        string ssid = cid.ToString();
                        if (!Global._CourseStudentAttendanceIdxDict.ContainsKey(ssid))
                            Global._CourseStudentAttendanceIdxDict.Add(ssid, coIdx);
                        drTT["缺曠紀錄" + coIdx] = ssid;   
                        coIdx++;
                    }
                }

                dr["學年度"] = string.Join(",", syL.ToArray());
                dr["學期"] = string.Join(",", ssL.ToArray());
                dr["梯次"] = string.Join(",", smL.ToArray());

                    dt.Rows.Add(dr);
                    dtAtt.Rows.Add(drTT);
                    // 處理動態處理(缺曠)
                    Document docAtt = new Document();
                    docAtt.Sections.Clear();
                    docAtt.Sections.Add(docAtt.ImportNode(docTemplate.Sections[0], true));
                    _builder = new DocumentBuilder(docAtt);
                    docAtt.MailMerge.MergeField += new Aspose.Words.Reporting.MergeFieldEventHandler(MailMerge_MergeField);
                    docAtt.MailMerge.Execute(dtAtt);
                    int cot = 1;
                    Document doc1 = new Document();
                    doc1.Sections.Clear();
                    doc1.Sections.Add(doc1.ImportNode(docAtt.Sections[0], true));
                    doc1.MailMerge.Execute(dt);
                    doc1.MailMerge.RemoveEmptyParagraphs = true;
                    doc1.MailMerge.DeleteFields();
                    //// 清除多餘欄位
                    //int TabRowCount = doc1.Sections[0].Body.Tables[0].Rows.Count - 1;
                    //for (int idx = TabRowCount; idx >= cot; idx--)
                    //{
                    //    doc1.Sections[0].Body.Tables[0].Rows.RemoveAt(idx);
                    //}
                    docList.Add(doc1);
            }

            doc.Sections.Clear();
            foreach (Document doc2 in docList)
                doc.Sections.Add(doc.ImportNode(doc2.Sections[0], true));

            string reportNameW = "重補修缺課通知單";

            if(_SelectChkNotExam)
                reportNameW = "重補修缺課扣考通知單";
            else
                reportNameW = "重補修缺課通知單";

            pathW = Path.Combine(System.Windows.Forms.Application.StartupPath + "\\Reports", "");
            if (!Directory.Exists(pathW))
                Directory.CreateDirectory(pathW);
            pathW = Path.Combine(pathW, reportNameW + ".doc");

            if (File.Exists(pathW))
            {
                int i = 1;
                while (true)
                {
                    string newPathW = Path.GetDirectoryName(pathW) + "\\" + Path.GetFileNameWithoutExtension(pathW) + (i++) + Path.GetExtension(pathW);
                    if (!File.Exists(newPathW))
                    {
                        pathW = newPathW;
                        break;
                    }
                }
            }

            try
            {
                doc.Save(pathW, Aspose.Words.SaveFormat.Doc);

            }
            catch (Exception exow)
            {

            }

            doc = null;
            docList.Clear();

            GC.Collect();
            _bgWork.ReportProgress(100);
            #endregion
        }
コード例 #17
0
ファイル: PdfStamps.cs プロジェクト: ParallaxIT/tdb-ws
        private void btnCreatePdf_Click(object sender, EventArgs e)
        {
            string pdfToModify = textBoxPdfFilePath.Text.Trim();

            // create a PDF document
            Document document = new Document(pdfToModify);

            // set the license key
            document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

            // get the first page the PDF document
            PdfPage firstPage = document.Pages[0];

            string logoTransImagePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\img\evologo-100-trans.png");
            string logoOpaqueImagePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\img\evologo-100.jpg");

            // add an opaque image stamp in the top left corner of the first page
            // and make it semitransparent when rendered in PDF
            ImageElement imageStamp = new ImageElement(1, 1, logoOpaqueImagePath);
            imageStamp.Opacity = 50;
            AddElementResult addResult = firstPage.AddElement(imageStamp);

            // add a border for the image stamp
            RectangleElement imageBorderRectangleElement = new RectangleElement(1, 1, addResult.EndPageBounds.Width,
                                addResult.EndPageBounds.Height);
            firstPage.AddElement(imageBorderRectangleElement);

            // add a template stamp to the document repeated on each document page
            // the template contains an image and a text

            System.Drawing.Image logoImg = System.Drawing.Image.FromFile(logoTransImagePath);

            // calculate the template stamp location and size
            System.Drawing.SizeF imageSizePx = logoImg.PhysicalDimension;

            float imageWidthPoints = UnitsConverter.PixelsToPoints(imageSizePx.Width);
            float imageHeightPoints = UnitsConverter.PixelsToPoints(imageSizePx.Height);

            float templateStampXLocation = (firstPage.ClientRectangle.Width - imageWidthPoints) / 2;
            float templateStampYLocation = firstPage.ClientRectangle.Height / 4;

            // the stamp size is equal to image size in points
            Template templateStamp = document.AddTemplate(new System.Drawing.RectangleF(templateStampXLocation, templateStampYLocation,
                    imageWidthPoints, imageHeightPoints + 20));

            // set a semitransparent background color for template
            RectangleElement background = new RectangleElement(0, 0, templateStamp.ClientRectangle.Width, templateStamp.ClientRectangle.Height);
            background.BackColor = Color.White;
            background.Opacity = 25;
            templateStamp.AddElement(background);

            // add a true type font to the document
            System.Drawing.Font ttfFontBoldItalic = new System.Drawing.Font("Times New Roman", 10,
                        System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point);
            PdfFont templateStampTextFont = document.AddFont(ttfFontBoldItalic, true);

            // Add a text element to the template. You can add any other types of elements to a template like a HtmlToPdfElement.
            TextElement templateStampTextElement = new TextElement(3, 0, "This is the Stamp Text", templateStampTextFont);
            templateStampTextElement.ForeColor = System.Drawing.Color.DarkBlue;
            templateStamp.AddElement(templateStampTextElement);

            // Add an image with transparency to the template. You can add any other types of elements to a template like a HtmlToPdfElement.
            ImageElement templateStampImageElement = new ImageElement(0, 20, logoImg);
            // instruct the library to use transparency information
            templateStampImageElement.RenderTransparentImage = true;
            templateStamp.AddElement(templateStampImageElement);

            // add a border to template
            RectangleElement templateStampRectangleElement = new RectangleElement(0, 0, templateStamp.ClientRectangle.Width,
                        templateStamp.ClientRectangle.Height);
            templateStamp.AddElement(templateStampRectangleElement);

            // dispose the image
            logoImg.Dispose();

            string outFilePath = System.IO.Path.Combine(Application.StartupPath, "PdfStamps.pdf");

            // save the PDF document to disk
            try
            {
                document.Save(outFilePath);
            }
            finally
            {
                document.Close();
            }

            DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(outFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
コード例 #18
0
        void PrintMau(DataRow drData)
        {
            try
            {
                List<string> fieldNames = new List<string>() {"TEN_SO_YTE", "TEN_BENHVIEN",	"DIACHI_BENHVIEN",
                    "DIENTHOAI_BENHVIEN",		"MA_LUOTKHAM",	"ID_BENHNHAN",	"TEN_BENHNHAN",	"DIA_CHI",	"DOITUONG_KCB",
                    "NOI_CHIDINH",	"CHANDOAN",	"ID_PHIEU","ten_chitietdichvu",	"NAMSINH",	"TUOI",	"GIOI_TINH",
                    "MATHE_BHYT",	"Ket_qua",	"KET_LUAN",	"DE_NGHI",	"NGAYTHANGNAM","imgPath1","imgPath2","imgPath3","imgPath4"};
                List<string> Values = new List<string>() {  globalVariables.ParentBranch_Name,  globalVariables.Branch_Name,  globalVariables.Branch_Address,
                 globalVariables.Branch_Phone,Utility.sDbnull( drData["MA_LUOTKHAM"],""),Utility.sDbnull( drData["ID_BENHNHAN"],""),Utility.sDbnull( drData["TEN_BENHNHAN"],""),
                Utility.sDbnull( drData["dia_chi"],""),Utility.sDbnull( drData["ten_doituong_kcb"],""),Utility.sDbnull( drData["ten_phongchidinh"],""),Utility.sDbnull( drData["Chan_doan"],""),
                Utility.sDbnull( drData["id_chidinh"],""),Utility.sDbnull( drData["ten_chitietdichvu"],""),Utility.sDbnull( drData["nam_sinh"],""),Utility.sDbnull( drData["Tuoi"],""),Utility.sDbnull( drData["gioi_tinh"],""),
                Utility.sDbnull( drData["mathe_bhyt"],""),"","",
                "",Utility.FormatDateTime(globalVariables.SysDate),Utility.sDbnull( drData["Local1"],""),Utility.sDbnull( drData["Local2"],""),
                Utility.sDbnull( drData["Local3"],""),
                Utility.sDbnull( drData["Local4"],"")};

                DmucDichvuclsChitiet objDichvuchitiet = DmucDichvuclsChitiet.FetchByID(Utility.Int32Dbnull(txtIdDichvuChitiet.Text, -1));
                if (objDichvuchitiet == null)
                {
                    Utility.ShowMsg("Không lấy được thông tin dịch vụ CĐHA từ chi tiết chỉ định");
                    return;
                }
                DataTable dtDynamicValues = clsHinhanh.GetDynamicFieldsValues(objDichvuchitiet.IdChitietdichvu, objDichvuchitiet.Bodypart, objDichvuchitiet.ViewPosition, -1, Utility.Int32Dbnull(txtidchidinhchitiet.Text, -1));
                foreach (DataRow dr in dtDynamicValues.Rows)
                {
                    string SCode = Utility.sDbnull(dr[DynamicValue.Columns.Ma], "");
                    //string SName = Utility.sDbnull(dr[DynamicValue.Columns.mota], "");
                    string SValue = Utility.sDbnull(dr[DynamicValue.Columns.Giatri], "");
                    fieldNames.Add(SCode);
                    Values.Add(string.Format("{0}", SValue));
                    //Values.Add(string.Format("{0}{1}", SName, SValue));
                }
                string maubaocao = Application.StartupPath + @"\MauCDHA\" + docChuan;
                if (!File.Exists(maubaocao))
                {
                    Utility.ShowMsg("Chưa có mẫu báo cáo cho dịch vụ đang chọn. Bạn cần tạo mẫu và nhấn nút chọn mẫu để cập nhật cho dịch vụ đang thực hiện");
                    cmdBrowseMauChuan.Focus();
                    return;
                }
                string fileKetqua = string.Format("{0}{1}{2}{3}{4}", Path.GetDirectoryName(maubaocao), Path.DirectorySeparatorChar, Path.GetFileNameWithoutExtension(maubaocao), "_ketqua", Path.GetExtension(maubaocao));
                if ((drData != null) && File.Exists(maubaocao))
                {
                    doc = new Document(maubaocao);

                    if (doc == null)
                    {
                        Utility.ShowMsg("Không nạp được file word.");
                        return;
                    }
                    doc.MailMerge.MergeImageField += MailMerge_MergeImageField;
                    doc.MailMerge.MergeField += MailMerge_MergeField;
                    doc.MailMerge.Execute(fieldNames.ToArray(), Values.ToArray());

                    if (File.Exists(fileKetqua))
                    {
                        File.Delete(fileKetqua);
                    }
                    doc.Save(fileKetqua, SaveFormat.Doc);
                    string path = fileKetqua;
                    if (chkPreview.Checked)
                    {
                        if (File.Exists(path))
                        {
                            Process process = new Process();
                            try
                            {
                                process.StartInfo.FileName = path;
                                process.Start();
                                process.WaitForInputIdle();
                            }
                            catch
                            {
                            }
                        }
                    }
                    else
                    {
                        PrinterSettings printerSettings = new PrinterSettings();
                        printerSettings.DefaultPageSettings.Margins.Top = 0;
                        printerSettings.Copies = 1;

                        doc.Print(printerSettings);
                    }

                }
                else
                {
                    MessageBox.Show("Không tìm thấy biểu mẫu", "TThông báo", MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #19
0
        public void UpdatePageLayout()
        {
            //ExStart
            //ExFor:StyleCollection.Item(String)
            //ExFor:SectionCollection.Item(Int32)
            //ExFor:Document.UpdatePageLayout
            //ExSummary:Shows when to request page layout of the document to be recalculated.
            Document doc = new Document(MyDir + "Rendering.doc");

            // Saving a document to PDF or to image or printing for the first time will automatically
            // layout document pages and this information will be cached inside the document.
            doc.Save(MyDir + "Rendering.UpdatePageLayout1 Out.pdf");

            // Modify the document in any way.
            doc.Styles["Normal"].Font.Size = 6;
            doc.Sections[0].PageSetup.Orientation = Aspose.Words.Orientation.Landscape;

            // In the current version of Aspose.Words, modifying the document does not automatically rebuild
            // the cached page layout. If you want to save to PDF or render a modified document again,
            // you need to manually request page layout to be updated.
            doc.UpdatePageLayout();

            doc.Save(MyDir + "Rendering.UpdatePageLayout2 Out.pdf");
            //ExEnd
        }
コード例 #20
0
        public void UpdateFieldsBeforeRendering()
        {
            //ExStart
            //ExFor:Document.UpdateFields
            //ExId:UpdateFieldsBeforeRendering
            //ExSummary:Shows how to update all fields before rendering a document.
            Document doc = new Document(MyDir + "Rendering.doc");

            // This updates all fields in the document.
            doc.UpdateFields();

            doc.Save(MyDir + "Rendering.UpdateFields Out.pdf");
            //ExEnd
        }
コード例 #21
0
        public void SubsetFontsInPdf()
        {
            //ExStart
            //ExFor:PdfSaveOptions.EmbedFullFonts
            //ExId:Subset
            //ExSummary:Demonstrates how to set Aspose.Words to subset fonts in the output PDF.
            // Load the document to render.
            Document doc = new Document(MyDir + "Rendering.doc");

            // To subset fonts in the output PDF document, simply create new PdfSaveOptions and set EmbedFullFonts to false.
            PdfSaveOptions options = new PdfSaveOptions();
            options.EmbedFullFonts = false;

            // The output PDF will contain subsets of the fonts in the document. Only the glyphs used
            // in the document are included in the PDF fonts.
            doc.Save(MyDir + "Rendering.SubsetFonts Out.pdf");
            //ExEnd
        }
コード例 #22
0
ファイル: Form1.cs プロジェクト: kobeaaron110/ischool_DEV
        private void button1_Click(object sender, EventArgs e)
        {
            //未輸入電子報表名稱的檢查
            if (textBox1.Text.Trim() != "")
            {
                //主要的Word文件
                Document doc = new Document();
                doc.Sections.Clear();

                if (radioButton2.Checked)
                {
                    #region 班級電子報表
                    //建立一個班級電子報表
                    //傳入參數 : 報表名稱,學年度,學期,類型(學生/班級/教師/課程)
                    paperForClass = new SmartSchool.ePaper.ElectronicPaper(textBox1.Text, School.DefaultSchoolYear, School.DefaultSemester, SmartSchool.ePaper.ViewerType.Class);

                    MemoryStream stream = new MemoryStream();

                    Document each_page = new Document(template, "", LoadFormat.Doc, "");
                    each_page.Save(stream, SaveFormat.Doc);

                    //取得所選擇的班級ID
                    List<string> ClassID = K12.Presentation.NLDPanels.Class.SelectedSource;
                    foreach (string each in ClassID)
                    {
                        //傳參數給PaperItem
                        //格式 / 內容 / 對象的系統編號
                        paperForClass.Append(new PaperItem(PaperFormat.Office2003Doc, stream, each));
                    }

                    //開始上傳
                    SmartSchool.ePaper.DispatcherProvider.Dispatch(paperForClass);
                    #endregion
                }
                else
                {
                    #region 班級學生的電子報表
                    //建立一個學生電子報表
                    //傳入參數 : 報表名稱,學年度,學期,類型(學生/班級/教師/課程)
                    paperForStudent = new SmartSchool.ePaper.ElectronicPaper(textBox1.Text, School.DefaultSchoolYear, School.DefaultSemester, SmartSchool.ePaper.ViewerType.Student);

                    //學生個人的文件
                    Document each_page = new Document(template, "", LoadFormat.Doc, "");
                    MemoryStream stream = new MemoryStream();
                    each_page.Save(stream, SaveFormat.Doc);
                    doc.Sections.Add(doc.ImportNode(each_page.Sections[0], true)); //合併至doc

                    List<string> ClassID = K12.Presentation.NLDPanels.Class.SelectedSource; //取得畫面上所選班級的ID清單
                    List<StudentRecord> srList = Student.SelectByClassIDs(ClassID); //依據班級ID,取得學生物件
                    foreach (StudentRecord sr in srList)
                    {
                        //傳參數給PaperItem
                        //格式 / 內容 / 對象的系統編號
                        paperForStudent.Append(new PaperItem(PaperFormat.Office2003Doc, stream, sr.ID));
                    }

                    //開始上傳
                    SmartSchool.ePaper.DispatcherProvider.Dispatch(paperForStudent);
                    #endregion
                }
            }
            else
            {
                MessageBox.Show("請輸入電子報表名稱!!");
            }
        }
コード例 #23
0
        /// <summary>
        /// 下載預設樣板
        /// </summary>
        private void DownloadDefaultTemplate()
        {
            Document DefaultDoc = new Document(new MemoryStream(Properties.Resources.輔導資料紀錄表範本));

            if (DefaultDoc == null)
            {
                FISCA.Presentation.Controls.MsgBox.Show("預設範本發生錯誤無法產生.");
                return;
            }

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Word (*.doc)|*.doc";
            saveDialog.FileName = "輔導資料紀錄表範本";
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    DefaultDoc.Save(saveDialog.FileName);
                }
                catch (Exception ex)
                {
                    FISCA.Presentation.Controls.MsgBox.Show("儲存失敗。" + ex.Message);
                    return;
                }

                try
                {
                    System.Diagnostics.Process.Start(saveDialog.FileName);
                }
                catch (Exception ex)
                {
                    FISCA.Presentation.Controls.MsgBox.Show("開啟失敗。" + ex.Message);
                    return;
                }
            }
        }
コード例 #24
0
ファイル: ShapesDemo.cs プロジェクト: ParallaxIT/tdb-ws
        private void btnCreatePdf_Click(object sender, EventArgs e)
        {
            // create a PDF document
            Document document = new Document();

            // set the license key
            document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

            // add a page to the PDF document
            PdfPage firstPage = document.AddPage();

            // draw rectangle
            RectangleElement rectangle1 = new RectangleElement(10, 10, 150, 100);
            rectangle1.ForeColor = System.Drawing.Color.Blue;
            rectangle1.LineStyle.LineWidth = 5; // a 5 points line width
            rectangle1.LineStyle.LineJoinStyle = LineJoinStyle.RoundJoin;
            firstPage.AddElement(rectangle1);

            // draw colored rectangle
            RectangleElement rectangle2 = new RectangleElement(200, 10, 150, 100);
            rectangle2.ForeColor = System.Drawing.Color.Blue;
            rectangle2.BackColor = System.Drawing.Color.Green;
            firstPage.AddElement(rectangle2);

            // draw gradient colored rectangle
            RectangleElement rectangle3 = new RectangleElement(400, 25, 100, 50);
            rectangle3.ForeColor = System.Drawing.Color.Blue;
            rectangle3.Gradient = new GradientColor(GradientDirection.Vertical, System.Drawing.Color.Green, System.Drawing.Color.Blue);
            firstPage.AddElement(rectangle3);

            // draw ellipse
            EllipseElement ellipse1 = new EllipseElement(75, 200, 70, 50);
            ellipse1.ForeColor = System.Drawing.Color.Blue;
            ellipse1.LineStyle.LineDashStyle = LineDashStyle.Dash;
            firstPage.AddElement(ellipse1);

            // draw ellipse
            EllipseElement ellipse2 = new EllipseElement(275, 200, 70, 50);
            ellipse2.ForeColor = System.Drawing.Color.Blue;
            ellipse2.BackColor = System.Drawing.Color.Green;
            firstPage.AddElement(ellipse2);

            // draw ellipse
            EllipseElement ellipse3 = new EllipseElement(450, 200, 50, 25);
            ellipse3.ForeColor = System.Drawing.Color.Blue;
            ellipse3.Gradient = new GradientColor(GradientDirection.Vertical, System.Drawing.Color.Green, System.Drawing.Color.Blue);
            firstPage.AddElement(ellipse3);

            BezierCurveElement bezierCurve1 = new BezierCurveElement(10, 350, 100, 300, 200, 400, 300, 350);
            bezierCurve1.ForeColor = System.Drawing.Color.Blue;
            bezierCurve1.LineStyle.LineWidth = 3;
            bezierCurve1.LineStyle.LineJoinStyle = LineJoinStyle.RoundJoin;
            firstPage.AddElement(bezierCurve1);

            BezierCurveElement bezierCurve2 = new BezierCurveElement(10, 350, 100, 400, 200, 300, 300, 350);
            bezierCurve2.ForeColor = System.Drawing.Color.Green;
            bezierCurve2.LineStyle.LineWidth = 3;
            bezierCurve2.LineStyle.LineJoinStyle = LineJoinStyle.RoundJoin;
            firstPage.AddElement(bezierCurve2);

            string outFilePath = System.IO.Path.Combine(Application.StartupPath, "ShapesDemo.pdf");

            // save the PDF document to disk
            document.Save(outFilePath);

            // close the PDF document to release the resources
            document.Close();

            DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(outFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
コード例 #25
0
ファイル: PaymentSheets.cs プロジェクト: kobeaaron110/mdhs
        private void btnReport_Click(object sender, EventArgs e)
        {
            List<StudentByBus> studentbus = new List<StudentByBus>();
            StudentByBus CurrentStudentbus = new StudentByBus();
            string CurrentBusStopName = "";
            BusSetup bussetup = BusSetupDAO.SelectByBusYearAndRange(this.intSchoolYear.Value, cboBusRange.Text);
            //List<string> newStuNumberList = new List<string>();
            List<string> newStudentIDList = new List<string>();
            List<MySchoolModule.NewStudentRecord> newStu = new List<MySchoolModule.NewStudentRecord>();
            Dictionary<string, StudentByBus> studentbusRecord = new Dictionary<string, StudentByBus>();
            foreach (MySchoolModule.NewStudentRecord nsr in NewStudent.Instance.SelectedList)
            {
                //if (!newStuNumberList.Contains(nsr.Number))
                //    newStuNumberList.Add(nsr.Number);
                if (!newStudentIDList.Contains(nsr.UID))
                    newStudentIDList.Add(nsr.UID);
                newStu.Add(nsr);
            }

            studentbus = StudentByBusDAO.SelectByBusYearAndTimeNameAndStudntList(this.intSchoolYear.Value, cboBusRange.Text, newStudentIDList);
            foreach (StudentByBus var in studentbus)
                if (!studentbusRecord.ContainsKey(var.StudentID))
                    studentbusRecord.Add(var.StudentID, var);

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //if (!File.Exists(Application.StartupPath + "\\Customize\\校車繳費單樣版-新生.doc"))
            //{
            //    MessageBox.Show("『" + Application.StartupPath + "\\Customize\\校車繳費單樣版-新生.doc』檔案不存在,請確認後重新執行!");
            //    return;
            //}

            //Document Template = new Document(Application.StartupPath + "\\Customize\\校車繳費單樣版-新生.doc");
            Document Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_新生));
            //Document Template = new Document();
            //mPreference = TemplatePreference.GetInstance();
            //if (mPreference.UseDefaultTemplate)
            //    Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.校車繳費單樣版_新生));
            //else
            //    Template = new Aspose.Words.Document(mPreference.CustomizeTemplate);

            Document doc = new Document();

            Payment SelectPayment = cboPayment.SelectedItem as Payment;

            //新增收費明細。
            List<PaymentDetail> StudentDetails = new List<PaymentDetail>();

            SelectPayment.FillFull();
            List<PaymentDetail> Studentdetail = PaymentDetail.GetByTarget("NewStudent", newStudentIDList);
            List<PaymentDetail> CurrentDetails = new List<PaymentDetail>();
            List<PaymentHistory> historys = new List<PaymentHistory>();
            List<string> ids = new List<string>();
            if (Studentdetail.Count == 0)
            {
                foreach (MySchoolModule.NewStudentRecord nsr in NewStudent.Instance.SelectedList)
                {
                    PaymentDetail detail = new PaymentDetail(SelectPayment);    //設定「收費明細」所屬的收費。

                    detail.RefTargetID = NewStudent.Instance.SelectedList[0].UID;//搭乘校車新生ID。
                    detail.RefTargetType = "NewStudent";
                    detail.Amount = studentbusRecord[nsr.UID].BusMoney;                  //要收多少錢。
                    detail.Extensions.Add("校車收費年度", SelectPayment.SchoolYear.ToString());
                    detail.Extensions.Add("校車收費學期", SelectPayment.Semester.ToString());
                    detail.Extensions.Add("校車收費名稱", cboBusRange.SelectedItem.ToString());
                    detail.Extensions.Add("MergeField::代碼", textBusStop.Text);
                    detail.Extensions.Add("MergeField::站名", CurrentBusStopName);
                    detail.Extensions.Add("MergeField::" + "學號", NewStudent.Instance.SelectedList[0].Number);
                    detail.Extensions.Add("MergeField::" + "姓名", NewStudent.Instance.SelectedList[0].Name);
                    detail.Extensions.Add("MergeField::" + "科別", NewStudent.Instance.SelectedList[0].Dept);
                    detail.Extensions.Add("開始日期", bussetup.BusStartDate.ToString());
                    detail.Extensions.Add("結束日期", bussetup.BusEndDate.ToString());
                    detail.Extensions.Add("搭車天數", studentbusRecord[nsr.UID].DateCount.ToString());
                    StudentDetails.Add(detail);                                 //先加到一個 List 中。
                }
                List<string> detailIDs = new List<string>();
                detailIDs = PaymentDetail.Insert(StudentDetails.ToArray());     //新增到資料庫中。

                //如果要馬上使用物件的話,需要用回傳的 UID 清單再將資料 Select 出來
                //因為這樣物件中才會包含 UID 資料。
                CurrentDetails = PaymentDetail.GetByIDs(detailIDs.ToArray());

                foreach (PaymentDetail pd in CurrentDetails)
                {
                    MotherForm.SetStatusBarMessage("條碼產生中....");
                    Application.DoEvents();
                    //新增一筆繳費記錄。
                    PaymentHistory history = new PaymentHistory(pd);
                    history.Amount = pd.Amount; //通常會與金額與繳費明細一樣。
                    ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                    historys.Add(history);
                }
                ids = PaymentHistory.Insert(historys);
            }
            else
            {
                foreach (PaymentDetail pdetail in Studentdetail)
                {
                    CurrentDetails.Add(pdetail);
                    pdetail.FillHistories();
                    if (pdetail.Extensions["校車收費名稱"] == cboBusRange.SelectedItem.ToString() && int.Parse(pdetail.Extensions["校車收費年度"]) == intSchoolYear.Value)
                    {
                        if (CancelExist.Checked)
                        {
                            //註銷先前之繳費單
                            pdetail.CancelExistReceipts();

                            if (studentbusRecord[pdetail.RefTargetID].DateCount > 0)
                            {
                                pdetail.Extensions["搭車天數"] = studentbusRecord[pdetail.RefTargetID].DateCount.ToString();
                                pdetail.Amount = studentbusRecord.ContainsKey(pdetail.RefTargetID) ? studentbusRecord[pdetail.RefTargetID].BusMoney : 0;
                                PaymentDetail.Update(pdetail);
                            }

                            MotherForm.SetStatusBarMessage("條碼產生中....");
                            Application.DoEvents();
                            //新增一筆繳費記錄。
                            PaymentHistory history = new PaymentHistory(pdetail);
                            history.Amount = pdetail.Amount;                                        //通常會與金額與繳費明細一樣。
                            ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history);    //計算條碼資料,計算時需要「Payment」物件。
                            historys.Add(history);
                        }
                        else
                        {
                            IList<PaymentHistory> historyss = pdetail.Histories;

                            if (historyss == null)
                                return;
                            foreach (PaymentHistory history in historyss)
                            {
                                ((Payment)cboPayment.SelectedItem).CalculateReceiptBarcode(history); //計算條碼資料,計算時需要「Payment」物件。
                                ids.Add(history.UID);
                            }
                        }
                    }
                }
                if (CancelExist.Checked)
                    ids = PaymentHistory.Insert(historys);
            }

            historys = PaymentHistory.GetByIDs(ids.ToArray());
            //產生繳費單
            ReceiptDocument rdoc = new ReceiptDocument(Template); //如果要自定樣版,可以用這個建構式。
            List<PaymentReceipt> prRecood = new List<PaymentReceipt>();
            foreach (PaymentHistory history in historys)
            {
                MotherForm.SetStatusBarMessage("繳費單產生中....");
                Application.DoEvents();
                prRecood.Add(history.Receipt);
            }
            doc = rdoc.Generate1(prRecood);

            if (doc.Sections.Count != 0)
            {
                string path = Path.Combine(Application.StartupPath, "Reports");
                string reportName = "繳費單";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                path = Path.Combine(path, reportName + ".doc");

                if (File.Exists(path))
                {
                    int i = 1;
                    while (true)
                    {
                        string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                        if (!File.Exists(newPath))
                        {
                            path = newPath;
                            break;
                        }
                    }
                }

                try
                {
                    doc.Save(path, SaveFormat.Doc);
                    System.Diagnostics.Process.Start(path);
                }
                catch
                {
                    System.Windows.Forms.SaveFileDialog sd1 = new System.Windows.Forms.SaveFileDialog();
                    sd1.Title = "另存新檔";
                    sd1.FileName = "繳費單.doc";
                    sd1.Filter = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*";
                    if (sd1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        try
                        {
                            doc.Save(sd1.FileName, SaveFormat.Doc);
                            System.Diagnostics.Process.Start(sd1.FileName);
                        }
                        catch
                        {
                            System.Windows.Forms.MessageBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
            }

            MotherForm.SetStatusBarMessage("繳費單產生完成。");
            this.Close();
        }
コード例 #26
0
        public void SetPdfEncryptionPermissions()
        {
            //ExStart
            //ExFor:PdfEncryptionDetails.#ctor
            //ExFor:PdfSaveOptions.EncryptionDetails
            //ExFor:PdfEncryptionDetails.Permissions
            //ExFor:PdfEncryptionAlgorithm
            //ExFor:PdfPermissions
            //ExFor:PdfEncryptionDetails
            //ExSummary:Demonstrates how to set permissions on a PDF document generated by Aspose.Words.
            Document doc = new Document(MyDir + "Rendering.doc");

            PdfSaveOptions saveOptions = new PdfSaveOptions();

            // Create encryption details and set owner password.
            PdfEncryptionDetails encryptionDetails = new PdfEncryptionDetails(string.Empty, "password", PdfEncryptionAlgorithm.RC4_128);

            // Start by disallowing all permissions.
            encryptionDetails.Permissions = PdfPermissions.DisallowAll;

            // Extend permissions to allow editing or modifying annotations.
            encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
            saveOptions.EncryptionDetails = encryptionDetails;

            // Render the document to PDF format with the specified permissions.
            doc.Save(MyDir + "Rendering.SpecifyPermissions Out.pdf", saveOptions);
            //ExEnd
        }
コード例 #27
0
 //報表產生完成後,儲存並且開啟
 private void Completed(string inputReportName, Document inputDoc)
 {
     SaveFileDialog sd = new SaveFileDialog();
     sd.Title = "另存新檔";
     sd.FileName = inputReportName + DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss") + ".doc";
     sd.Filter = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*";
     sd.AddExtension = true;
     if (sd.ShowDialog() == DialogResult.OK)
     {
         try
         {
             inputDoc.Save(sd.FileName, Aspose.Words.SaveFormat.Doc);
             System.Diagnostics.Process.Start(sd.FileName);
         }
         catch
         {
             MsgBox.Show("指定路徑無法存取。", "建立檔案失敗", MessageBoxButtons.OK, MessageBoxIcon.Error);
             return;
         }
     }
 }
コード例 #28
0
ファイル: IDEApplication.cs プロジェクト: pavelsavara/nMars
 public bool SaveDocument(Document doc)
 {
     bool res = doc.Save();
     RefreshControls();
     return res;
 }
コード例 #29
0
ファイル: frmLogin.cs プロジェクト: vanloc0301/mychongchong
 private void SaveSettings()
 {
     Document document = new Document();
     Element element = new Element("Settings");
     Element element2 = new Element("Login");
     element2.get_ChildNodes().Add(new Element("Jid", this.txtJid.Text));
     element2.get_ChildNodes().Add(new Element("Password", this.txtPassword.Text));
     element2.get_ChildNodes().Add(new Element("Resource", this.txtResource.Text));
     element2.get_ChildNodes().Add(new Element("Priority", this.numPriority.Value.ToString()));
     element2.get_ChildNodes().Add(new Element("Port", this.txtPort.Text));
     element2.get_ChildNodes().Add(new Element("Ssl", this.chkSSL.Checked));
     document.get_ChildNodes().Add(element);
     element.get_ChildNodes().Add(element2);
     document.Save(this.SettingsFilename);
 }
コード例 #30
0
        public void SetDefaultFontName()
        {
            //ExStart
            //ExFor:FontSettings.DefaultFontName
            //ExId:SetDefaultFontName
            //ExSummary:Demonstrates how to specify what font to substitute for a missing font during rendering.
            Document doc = new Document(MyDir + "Rendering.doc");

            // If the default font defined here cannot be found during rendering then the closest font on the machine is used instead.
            FontSettings.DefaultFontName = "Arial Unicode MS";

            // Now the set default font is used in place of any missing fonts during any rendering calls.
            doc.Save(MyDir + "Rendering.SetDefaultFont Out.pdf");
            doc.Save(MyDir + "Rendering.SetDefaultFont Out.xps");
            //ExEnd
        }