Beispiel #1
0
        public void Sign(string filenameDest)
        {
            PdfSecuritySettings securitySettings = document.SecuritySettings;

            // Setting one of the passwords automatically sets the security level to
            // PdfDocumentSecurityLevel.Encrypted128Bit.
            securitySettings.UserPassword  = "******";
            securitySettings.OwnerPassword = "******";

            // Don't use 40 bit encryption unless needed for compatibility
            //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

            // Restrict some rights.
            securitySettings.PermitAccessibilityExtractContent = false;
            securitySettings.PermitAnnotations      = false;
            securitySettings.PermitAssembleDocument = false;
            securitySettings.PermitExtractContent   = false;
            securitySettings.PermitFormsFill        = true;
            securitySettings.PermitFullQualityPrint = false;
            securitySettings.PermitModifyDocument   = true;
            securitySettings.PermitPrint            = false;

            // Save the document...
            document.Save(filenameDest);
            // ...and start a viewer.
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            // Open an existing document. Providing an unrequired password is ignored.
            var         filename = @"";
            PdfDocument document = PdfReader.Open(filename, "some text");

            PdfSecuritySettings securitySettings = document.SecuritySettings;

            // Setting one of the passwords automatically sets the security level to
            // PdfDocumentSecurityLevel.Encrypted128Bit.
            securitySettings.UserPassword  = "******";
            securitySettings.OwnerPassword = "******";

            // Don't use 40 bit encryption unless needed for compatibility reasons
            //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

            // Restrict some rights.
            securitySettings.PermitAccessibilityExtractContent = false;
            securitySettings.PermitAnnotations      = false;
            securitySettings.PermitAssembleDocument = false;
            securitySettings.PermitExtractContent   = false;
            securitySettings.PermitFormsFill        = true;
            securitySettings.PermitFullQualityPrint = false;
            securitySettings.PermitModifyDocument   = true;
            securitySettings.PermitPrint            = false;

            // Save the document...
            document.Save(@"");
        }
Beispiel #3
0
        private void ProtectFile(string filenameDest, string ownerPw, string userPw)
        {
            // Open an existing document. Providing an unrequired password is ignored.
            PdfDocument document = PdfReader.Open(filenameDest, "some text");

            PdfSecuritySettings securitySettings = document.SecuritySettings;

            // Setting one of the passwords automatically sets the security level to
            // PdfDocumentSecurityLevel.Encrypted128Bit.
            securitySettings.UserPassword  = userPw;
            securitySettings.OwnerPassword = ownerPw;

            // Don't use 40 bit encryption unless needed for compatibility
            //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

            // Restrict some rights.
            securitySettings.PermitAccessibilityExtractContent = false;
            securitySettings.PermitAnnotations      = false;
            securitySettings.PermitAssembleDocument = false;
            securitySettings.PermitExtractContent   = false;
            securitySettings.PermitFormsFill        = true;
            securitySettings.PermitFullQualityPrint = false;
            securitySettings.PermitModifyDocument   = false;
            securitySettings.PermitPrint            = true;


            // Save the document...
            document.Save(filenameDest);
            // ...and start a viewer.
            //Process.Start(filenameDest);
        }
Beispiel #4
0
        public static void ProtectDocument()
        {
            // Open an existing document.
            PdfDocument document = PdfReader.Open("file1.pdf");

            PdfSecuritySettings securitySettings = document.SecuritySettings;

            // Add user password and owner password
            securitySettings.UserPassword  = "******";
            securitySettings.OwnerPassword = "******";

            // Set passwords security level
            securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted128Bit;

            // Restrict permission rights. Disallow all the editing rights.
            securitySettings.PermitAccessibilityExtractContent = false;
            securitySettings.PermitAnnotations      = false;
            securitySettings.PermitAssembleDocument = false;
            securitySettings.PermitExtractContent   = false;
            securitySettings.PermitFormsFill        = false;
            securitySettings.PermitFullQualityPrint = false;
            securitySettings.PermitModifyDocument   = false;
            securitySettings.PermitPrint            = false;

            // Save the document...
            document.Save("Protect.pdf");
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            string[] fileGroup = Directory.GetFiles(
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\", "*.pdf"
                );

            foreach (string fileName in (from f in fileGroup
                                         where !f.Contains("-Kennwort")
                                         select f).ToList())
            {
                PdfDocument         document         = PdfReader.Open(fileName);
                PdfSecuritySettings securitySettings = document.SecuritySettings;
                securitySettings.UserPassword  = "******";
                securitySettings.OwnerPassword = "******";
                securitySettings.PermitAccessibilityExtractContent = false;
                securitySettings.PermitAnnotations      = false;
                securitySettings.PermitAssembleDocument = false;
                securitySettings.PermitExtractContent   = false;
                securitySettings.PermitFormsFill        = true;
                securitySettings.PermitFullQualityPrint = false;
                securitySettings.PermitModifyDocument   = true;
                securitySettings.PermitPrint            = false;
                document.Save(fileName.Replace(".pdf", "-Kennwort.pdf"));
            }
        }
Beispiel #6
0
        private void SetPassword(PdfDocumentRenderer renderer, string password)
        {
            PdfSecuritySettings securitySettings = renderer.PdfDocument.SecuritySettings;

            securitySettings.OwnerPassword = password;
            securitySettings.UserPassword  = password;
            securitySettings.PermitAccessibilityExtractContent = false;
            securitySettings.PermitAnnotations      = false;
            securitySettings.PermitAssembleDocument = false;
            securitySettings.PermitExtractContent   = false;
            securitySettings.PermitFormsFill        = false;
            securitySettings.PermitFullQualityPrint = false;
            securitySettings.PermitModifyDocument   = false;
            securitySettings.PermitPrint            = false;
        }
Beispiel #7
0
        public bool ConvertHtmlToPdf(int RequestID)
        {
            var payslips = _payslipDetailReponsitory.FindAll().Where(x => x.RequestID == RequestID).ToList();
            var request  = _requestDetailService.GetById(RequestID);
            var temp     = _requestDetailReponsitory.FindById(RequestID);

            _requestDetailReponsitory.Commit();
            string month = months[request.PayslipForMonth];

            if (payslips == null)
            {
                return(false);
            }

            foreach (var item in payslips)
            {
                PdfDocument  checkPDF        = null;
                InputPdfFile model           = InputPdfFile(item);
                string       StringHtml      = _viewRenderService.RenderToStringAsync(@"../../Pages/PayslipTemplate", model).GetAwaiter().GetResult();
                string       folderPath      = @"..\OSDPayslip.Web\wwwroot\PDF\" + RequestID.ToString();
                string       pdfPath         = folderPath + @"\" + model.Id + "_Payslips_" + month + ".pdf";
                var          pdfPrintOptions = new PdfPrintOptions()
                {
                    DPI = 300,
                };

                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                HtmlToPdf Renderer = new HtmlToPdf(pdfPrintOptions);
                Renderer.PrintOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A2;
                checkPDF = Renderer.RenderHtmlAsPdf(StringHtml).SaveAs(pdfPath);
                if (checkPDF != null)
                {
                    PdfDocument         Pdf = PdfDocument.FromFile(pdfPath);
                    PdfSecuritySettings securitySettings = Pdf.SecuritySettings;
                    securitySettings.UserPassword = CreatePassWord(model.IdentidyId, model.BirthDay);
                    if (Pdf.Password != null)
                    {
                        Pdf.SaveAs(pdfPath);
                    }
                }
            }

            return(true);
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            try
            {
                // Get a fresh copy of the sample PDF file.
                const string filenameSource = "BLKey.pdf";
                const string filenameDest   = "BLKey.pdf";
                File.Copy(Path.Combine("C:\\Users\\knasdmd\\Downloads", filenameSource),
                          Path.Combine(Directory.GetCurrentDirectory(), filenameDest), true);

                // Open an existing document. Providing an unrequired password is ignored.
                PdfDocument document = PdfReader.Open(filenameDest, "no_password_required");

                PdfSecuritySettings securitySettings = document.SecuritySettings;

                // Setting one of the passwords automatically sets the security level to
                // PdfDocumentSecurityLevel.Encrypted128Bit.
                securitySettings.UserPassword  = "";
                securitySettings.OwnerPassword = "";

                // Don't use 40 bit encryption unless needed for compatibility
                //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

                // Restrict some rights.
                securitySettings.PermitAccessibilityExtractContent = false;
                securitySettings.PermitAnnotations      = false;
                securitySettings.PermitAssembleDocument = false;
                securitySettings.PermitExtractContent   = false;
                securitySettings.PermitFormsFill        = true;
                securitySettings.PermitFullQualityPrint = false;
                securitySettings.PermitModifyDocument   = true;
                securitySettings.PermitPrint            = false;

                // Save the document...
                document.Save(filenameDest);
                // ...and start a viewer.
                Process.Start(filenameDest);

                Console.WriteLine("Password assigned");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #9
0
        // This sample shows how to protect a document with a password.
        protected override void DoWork()
        {
            // Get a fresh copy of the sample PDF file
            const string filenameSource = "HelloWorld.pdf";
            const string filenameDest   = "HelloWorld_tempfile.pdf";

            File_Copy(Path.Combine("AltData/PDFsharp/PDFs/", filenameSource),
                      Path.Combine(Directory.GetCurrentDirectory(), filenameDest), true);

            // Open an existing document. Providing an unrequired password is ignored.
            PdfDocument document = PdfReader.Open(filenameDest, "some text");

            PdfSecuritySettings securitySettings = document.SecuritySettings;

            // Setting one of the passwords automatically sets the security level to
            // PdfDocumentSecurityLevel.Encrypted128Bit.
            securitySettings.UserPassword  = "******";
            securitySettings.OwnerPassword = "******";

            // Don't use 40 bit encryption unless needed for compatibility
            //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

            // Restrict some rights.
            securitySettings.PermitAccessibilityExtractContent = false;
            securitySettings.PermitAnnotations      = false;
            securitySettings.PermitAssembleDocument = false;
            securitySettings.PermitExtractContent   = false;
            securitySettings.PermitFormsFill        = true;
            securitySettings.PermitFullQualityPrint = false;
            securitySettings.PermitModifyDocument   = true;
            securitySettings.PermitPrint            = false;

            // Save the document...
            document.Save(filenameDest);
            // ...and start a viewer.
            Diagnostics.ProcessHelper.Start(filenameDest);
        }
Beispiel #10
0
        public static PdfDocument Create(Test test)
        {
            PdfDocument document = new PdfDocument();

            document.Info.Title = test.Name;

            PageSize        size = PageSize.A4;
            PageOrientation orientation;

            // Looks stupid, but PdfSharp has its own size classes
            switch (test.Paper.Template)
            {
            case (PaperTemplate.Letter):
                size = PageSize.Letter;
                break;

            case (PaperTemplate.GovernmentLetter):
                size = PageSize.GovernmentLetter;
                break;

            case (PaperTemplate.Legal):
                size = PageSize.Legal;
                break;

            case (PaperTemplate.Ledger):
                size = PageSize.Ledger;
                break;

            case (PaperTemplate.A0):
                size = PageSize.A0;
                break;

            case (PaperTemplate.A1):
                size = PageSize.A1;
                break;

            case (PaperTemplate.A2):
                size = PageSize.A2;
                break;

            case (PaperTemplate.A3):
                size = PageSize.A3;
                break;

            case (PaperTemplate.A4):
                size = PageSize.A4;
                break;

            case (PaperTemplate.A5):
                size = PageSize.A5;
                break;
            }

            if (test.Paper.Orientation == PaperOrientation.Portrait)
            {
                orientation = PageOrientation.Portrait;
            }
            else
            {
                orientation = PageOrientation.Landscape;
            }

            if (size == PageSize.GovernmentLetter || size == PageSize.Ledger)
            {
                orientation = orientation == PageOrientation.Portrait ? PageOrientation.Landscape : PageOrientation.Portrait;
            }

            foreach (Page page in test.Pages)
            {
                PdfPage pdfPage = document.AddPage();
                pdfPage.Size        = size;
                pdfPage.Orientation = orientation;
                XGraphics g = XGraphics.FromPdfPage(pdfPage);
                page.PdfDraw(g);
            }

            PdfSecuritySettings securitySettings = document.SecuritySettings;

            securitySettings.DocumentSecurityLevel             = PdfDocumentSecurityLevel.Encrypted128Bit;
            securitySettings.OwnerPassword                     = "******";
            securitySettings.PermitAccessibilityExtractContent = false;
            securitySettings.PermitAnnotations                 = false;
            securitySettings.PermitAssembleDocument            = false;
            securitySettings.PermitExtractContent              = false;
            securitySettings.PermitFormsFill                   = false;
            securitySettings.PermitFullQualityPrint            = false;
            securitySettings.PermitModifyDocument              = false;
            securitySettings.PermitPrint            = true;
            securitySettings.PermitFullQualityPrint = true;

            return(document);
        }
Beispiel #11
0
        /// <summary>
        /// Protects a PDF with a password
        /// </summary>
        /// <param name="filenameSource">Sourcefile</param>
        /// <param name="filenameDest">Destinationfile</param>
        /// <param name="openPass">Password needed to open Sourcefile</param>
        /// <param name="userPass">Password for Useraccess in Destinationfile</param>
        /// <param name="ownerPass">Password for Owneraccess in Destinationfile</param>
        public void protectPDF(String filenameSource, String filenameDest, String openPass, String userPass, String ownerPass)
        {
            String openfilename = "";

            if (filenameSource.Equals(filenameDest))
            {//Zieldatei gleich Quelldatei
                openfilename = filenameSource;
            }
            else
            {//Unterschiedliche Ziel und Quelldatei
                // Get a fresh copy of the sample PDF file   - overwrite file if exists
                File.Copy(filenameSource, filenameDest, true);
                openfilename = filenameDest;
            }


            PdfDocument document = null;

            try
            {
                // Open an existing document. Providing an unrequired password is ignored.
                document = PdfReader.Open(openfilename, openPass);
            }
            catch (Exception ex)
            {
                if (this.OnErrorOccured != null)
                {
                    this.OnErrorOccured(this, "Fehler beim Öffnen der Quelldatei (" + openfilename + "):\r\nIst diese bereits Kennwortgeschützt und das zum Öffnen erforderliche Kennwort nicht oder inkorrekt angegeben?");
                }
                return;
            }


            PdfSecuritySettings securitySettings = document.SecuritySettings;

            // Setting one of the passwords automatically sets the security level to
            // PdfDocumentSecurityLevel.Encrypted128Bit.
            securitySettings.UserPassword  = userPass;
            securitySettings.OwnerPassword = ownerPass;

            // Don't use 40 bit encryption unless needed for compatibility
            //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

            // Restrict some user rights.
            securitySettings.PermitAccessibilityExtractContent = this.UserOptions["AllowExtract"];
            securitySettings.PermitAnnotations      = this.UserOptions["AllowComments"];
            securitySettings.PermitAssembleDocument = this.UserOptions["AllowAssembleDocument"];
            securitySettings.PermitExtractContent   = this.UserOptions["AllowExtract"];
            securitySettings.PermitFormsFill        = this.UserOptions["AllowEditFillForms"];
            securitySettings.PermitFullQualityPrint = false;
            securitySettings.PermitModifyDocument   = this.UserOptions["AllowEditFillForms"];
            securitySettings.PermitPrint            = this.UserOptions["AllowPrintDocument"];

            /*
             * securitySettings.PermitAccessibilityExtractContent = false;
             * securitySettings.PermitAnnotations = false;
             * securitySettings.PermitAssembleDocument = false;
             * securitySettings.PermitExtractContent = false;
             * securitySettings.PermitFormsFill = true;
             * securitySettings.PermitFullQualityPrint = false;
             * securitySettings.PermitModifyDocument = true;
             * securitySettings.PermitPrint = false;
             */

            // Save the document...
            document.Save(filenameDest);
            document.Close();

            if (this.OnSuccess != null)
            {
                this.OnSuccess(this, "Die Datei \"" + openfilename + "\" wurde erfolgreich mit einem Kennwortschutz versehen.");
            }
            // ...and start a viewer.
            // Process.Start(filenameDest);
        }
Beispiel #12
0
        // Perform some post-processing on the generated PDF
        private static void postProcessPDFFile(String generatedFile, String finalFile, Hashtable options, Boolean postProcessPDFSecurity)
        {
            // Handle PDF merging
            if ((MergeMode)options["pdf_merge"] != MergeMode.None)
            {
                if ((Boolean)options["verbose"])
                {
                    Console.WriteLine("Merging with existing PDF");
                }
                PdfDocument srcDoc;
                PdfDocument dstDoc = null;
                if ((MergeMode)options["pdf_merge"] == MergeMode.Append)
                {
                    srcDoc = PdfReader.Open(generatedFile, PdfDocumentOpenMode.Import);
                    dstDoc = readExistingPDFDocument(finalFile, generatedFile, ((string)options["pdf_owner_pass"]).Trim(), PdfDocumentOpenMode.Modify);
                }
                else
                {
                    dstDoc = PdfReader.Open(generatedFile, PdfDocumentOpenMode.Modify);
                    srcDoc = readExistingPDFDocument(finalFile, generatedFile, ((string)options["pdf_owner_pass"]).Trim(), PdfDocumentOpenMode.Import);
                }
                int pages = srcDoc.PageCount;
                for (int pi = 0; pi < pages; pi++)
                {
                    PdfPage page = srcDoc.Pages[pi];
                    dstDoc.AddPage(page);
                }
                dstDoc.Save(finalFile);
                File.Delete(generatedFile);
            }

            if (options["pdf_page_mode"] != null || options["pdf_layout"] != null ||
                (MetaClean)options["pdf_clean_meta"] != MetaClean.None || postProcessPDFSecurity)
            {
                PdfDocument pdf = PdfReader.Open(finalFile, PdfDocumentOpenMode.Modify);

                if (options["pdf_page_mode"] != null)
                {
                    if ((Boolean)options["verbose"])
                    {
                        Console.WriteLine("Setting PDF Page mode");
                    }
                    pdf.PageMode = (PdfPageMode)options["pdf_page_mode"];
                }
                if (options["pdf_layout"] != null)
                {
                    if ((Boolean)options["verbose"])
                    {
                        Console.WriteLine("Setting PDF layout");
                    }
                    pdf.PageLayout = (PdfPageLayout)options["pdf_layout"];
                }

                if ((MetaClean)options["pdf_clean_meta"] != MetaClean.None)
                {
                    if ((Boolean)options["verbose"])
                    {
                        Console.WriteLine("Cleaning PDF meta-data");
                    }
                    pdf.Info.Creator  = "";
                    pdf.Info.Keywords = "";
                    pdf.Info.Author   = "";
                    pdf.Info.Subject  = "";
                    pdf.Info.Producer = "";
                    if ((MetaClean)options["pdf_clean_meta"] == MetaClean.Full)
                    {
                        pdf.Info.Title            = "";
                        pdf.Info.CreationDate     = System.DateTime.Today;
                        pdf.Info.ModificationDate = System.DateTime.Today;
                    }
                }

                // See if there are security changes needed
                if (postProcessPDFSecurity)
                {
                    PdfSecuritySettings secSettings = pdf.SecuritySettings;
                    if (((string)options["pdf_owner_pass"]).Trim().Length != 0)
                    {
                        // Set the owner password
                        if ((Boolean)options["verbose"])
                        {
                            Console.WriteLine("Setting PDF owner password");
                        }
                        secSettings.OwnerPassword = ((string)options["pdf_owner_pass"]).Trim();
                    }
                    if (((string)options["pdf_user_pass"]).Trim().Length != 0)
                    {
                        // Set the user password
                        // Set the owner password
                        if ((Boolean)options["verbose"])
                        {
                            Console.WriteLine("Setting PDF user password");
                        }
                        secSettings.UserPassword = ((string)options["pdf_user_pass"]).Trim();
                    }

                    secSettings.PermitAccessibilityExtractContent = !(Boolean)options["pdf_restrict_accessibility_extraction"];
                    secSettings.PermitAnnotations      = !(Boolean)options["pdf_restrict_annotation"];
                    secSettings.PermitAssembleDocument = !(Boolean)options["pdf_restrict_assembly"];
                    secSettings.PermitExtractContent   = !(Boolean)options["pdf_restrict_extraction"];
                    secSettings.PermitFormsFill        = !(Boolean)options["pdf_restrict_forms"];
                    secSettings.PermitModifyDocument   = !(Boolean)options["pdf_restrict_modify"];
                    secSettings.PermitPrint            = !(Boolean)options["pdf_restrict_print"];
                    secSettings.PermitFullQualityPrint = !(Boolean)options["pdf_restrict_full_quality"];
                }
                pdf.Save(finalFile);
                pdf.Close();
            }
        }
Beispiel #13
0
        public void Getpdf(string pass, string path, string passAdmin)
        {
            try
            {
                // Get a fresh copy of the sample PDF file
                //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                //string filenameDest = "OriginalFile.pdf";

                //File.Copy(Path.Combine(path),
                //Path.Combine(desktopPath, filenameDest), true);

                // Open an existing document. Providing an unrequired password is ignored.

                PdfDocument document = PdfReader.Open(path, "some text");

                PdfSecuritySettings securitySettings = document.SecuritySettings;

                // Setting one of the passwords automatically sets the security level to
                // PdfDocumentSecurityLevel.Encrypted128Bit.
                securitySettings.UserPassword  = pass;
                securitySettings.OwnerPassword = passAdmin;



                // Don't use 40 bit encryption unless needed for compatibility
                //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

                // Restrict some rights.
                if (checkBox1.Checked == true)
                {
                    securitySettings.PermitAccessibilityExtractContent = true;
                }
                else
                {
                    securitySettings.PermitAccessibilityExtractContent = false;
                }

                if (checkBox2.Checked == true)
                {
                    securitySettings.PermitAnnotations = true;
                }
                else
                {
                    securitySettings.PermitAnnotations = false;
                }

                if (checkBox3.Checked == true)
                {
                    securitySettings.PermitAssembleDocument = true;
                }
                else
                {
                    securitySettings.PermitAssembleDocument = false;
                }

                if (checkBox4.Checked == true)
                {
                    securitySettings.PermitExtractContent = true;
                }
                else
                {
                    securitySettings.PermitExtractContent = false;
                }
                if (checkBox5.Checked == true)
                {
                    securitySettings.PermitFormsFill = true;
                }
                else
                {
                    securitySettings.PermitFormsFill = false;
                }

                if (checkBox6.Checked == true)
                {
                    securitySettings.PermitFullQualityPrint = true;
                }
                else
                {
                    securitySettings.PermitFullQualityPrint = false;
                }

                if (checkBox7.Checked == true)
                {
                    securitySettings.PermitModifyDocument = true;
                }
                else
                {
                    securitySettings.PermitModifyDocument = false;
                }
                if (checkBox8.Checked == true)
                {
                    securitySettings.PermitPrint = true;
                }
                else
                {
                    securitySettings.PermitPrint = false;
                }



                // Save the document...
                document.Save(path);
                // ...and start a viewer.
                MessageBox.Show("Encrpted PDF Success");

                textBox1.Text     = "";
                textBox2.Text     = "";
                checkBox1.Checked = false;
                checkBox2.Checked = false;
                checkBox3.Checked = false;
                checkBox4.Checked = false;
                checkBox5.Checked = false;
                checkBox6.Checked = false;
                checkBox7.Checked = false;
                checkBox8.Checked = false;
                checkBox9.Checked = false;
                Process.Start(path);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }
Beispiel #14
0
        internal Excelzeile Notenliste(
            Application application,
            Workbook workbook,
            List <Schueler> schuelers,
            Lehrers lehrers)
        {
            Console.Write(NameUntis.PadRight(6) + ": Excel-Notenliste erzeugen ... ");

            Worksheet deckblatt = workbook.Worksheets.get_Item(1);

            deckblatt.Copy(Type.Missing, workbook.Sheets[workbook.Sheets.Count]);
            workbook.Sheets[workbook.Sheets.Count].Name = NameUntis + "-D";
            var worksheet = workbook.Sheets[NameUntis + "-D"];

            worksheet.Activate();

            worksheet.Cells[7, 2]  = "Prüfung: Sommer " + DateTime.Now.Year;
            worksheet.Cells[10, 3] = NameUntis;
            worksheet.Cells[10, 6] = Klassenleitungen[0].Vorname + " " + Klassenleitungen[0].Nachname;

            // Lehrer auf dem Deckblatt auflisten

            int z = 16;

            foreach (var lehrerkürzel in (from s in schuelers from f in s.Fächer orderby f.Lehrerkürzel select f.Lehrerkürzel).Distinct())
            {
                worksheet.Cells[z, 2] = (from l in lehrers where l.Kürzel == lehrerkürzel select l.Nachname + ", " + l.Vorname).FirstOrDefault();

                var fächer = (from s in schuelers
                              from f in s.Fächer
                              where f.Lehrerkürzel == lehrerkürzel
                              where !f.KürzelUntis.EndsWith(" FU")
                              select f.KürzelUntis).Distinct().ToList();
                var ff = "";
                foreach (var fach in fächer)
                {
                    ff += fach + ",";
                }
                worksheet.Cells[z, 6] = ff.TrimEnd(',');
                z++;
            }

            Worksheet vorlage = workbook.Sheets["Liste"];

            if (NameUntis == "BSO")
            {
                vorlage = workbook.Sheets["Liste-BSO"];
            }

            vorlage.Copy(Type.Missing, workbook.Sheets[workbook.Sheets.Count]);
            workbook.Sheets[workbook.Sheets.Count].Name = NameUntis + "-L";
            worksheet = workbook.Sheets[NameUntis + "-L"];
            worksheet.Activate();

            worksheet.PageSetup.LeftHeader = "Prüfungsliste";
            //worksheet.PageSetup.CenterHeader = "Abschlusskonferenz";
            //worksheet.PageSetup.RightHeader = DateTime.Now.ToLocalTime();

            worksheet.Cells[1, 1] = "Klasse: " + this.NameUntis + "         Klassenleitung: " + this.Klassenleitungen[0].Vorname + " " + this.Klassenleitungen[0].Nachname + "        " + "Schuljahr: " + Global.AktSjAtl;
            //worksheet.Cells.Font.Size = 12;

            int zeileObenLinks  = 3;
            int spalteObenlinks = 1;

            foreach (var schueler in schuelers.OrderBy(x => x.Nachname).ThenBy(y => y.Vorname).ToList())
            {
                worksheet.Cells[zeileObenLinks + 2, spalteObenlinks] = schueler.Nachname + ", " + schueler.Vorname;
                worksheet.Cells[zeileObenLinks + 3, spalteObenlinks] = "*" + schueler.Gebdat.ToShortDateString();

                if (NameUntis == "BSO")
                {
                    worksheet.Cells[zeileObenLinks + 5, spalteObenlinks + 1] = "";
                    worksheet.Cells[zeileObenLinks + 6, spalteObenlinks + 1] = "";
                    worksheet.Cells[zeileObenLinks + 7, spalteObenlinks + 1] = "";
                }

                int x = 0;

                foreach (var fach in (from f in schueler.Fächer
                                      where f.KürzelUntis != null
                                      where f.KürzelUntis != ""
                                      where f.Lehrerkürzel != null
                                      where f.Lehrerkürzel != ""
                                      where !f.KürzelUntis.EndsWith("FU")
                                      select f).OrderBy(y => y.Nummer).Distinct().ToList())
                {
                    worksheet.Cells[zeileObenLinks + 1, spalteObenlinks + 2 + x] = fach.Lehrerkürzel;
                    worksheet.Cells[zeileObenLinks + 2, spalteObenlinks + 2 + x] = fach.KürzelUntis;

                    // Wenn der Schüler auch BWR hat, wird aus IF WI

                    if (fach.KürzelUntis == "IF")
                    {
                        if ((from f in schueler.Fächer
                             where f.KürzelUntis.StartsWith("BWR")
                             select f.KürzelUntis).Any())
                        {
                            worksheet.Cells[zeileObenLinks + 2, spalteObenlinks + 2 + x] = "WI";
                        }
                    }

                    worksheet.Cells[zeileObenLinks + 3, spalteObenlinks + 2 + x] = fach.Note == null ? "" : fach.Note.Substring(0, Math.Min(fach.Note.Length, 1));

                    if (NameUntis.Contains("13"))
                    {
                        worksheet.Cells[zeileObenLinks + 3, spalteObenlinks + 2 + x] = fach.Note;
                    }

                    x++;
                }
                zeileObenLinks = zeileObenLinks + 12;
            }

            // Liste für Homepage erstellen

            var teilnehmer = new List <Lehrer>
            {
                (from l in lehrers where l.Kürzel == Global.KürzelSchulleiter select l).FirstOrDefault(),
                (from l in lehrers where l.Kürzel == this.Bereichsleitung select l).FirstOrDefault()
            };

            teilnehmer.AddRange(this.Klassenleitungen);

            string kla = "";

            foreach (var item in Klassenleitungen)
            {
                kla += item.Vorname + " " + item.Nachname + ",";
            }

            Global.Excel2Pdf(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + NameUntis, NameUntis);

            Console.Write("Nach PDF umwandeln ... ");
            worksheet.ExportAsFixedFormat(
                XlFixedFormatType.xlTypePDF,
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + NameUntis,
                XlFixedFormatQuality.xlQualityStandard,
                true,
                true,
                1,
                Math.Ceiling((Double)schuelers.Count / 4.0),  // Letzte zu druckende Worksheetseite
                false);

            // Passwort protect pdf

            PdfDocument document = PdfReader.Open(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + NameUntis + ".pdf");

            PdfSecuritySettings securitySettings = document.SecuritySettings;

            securitySettings.UserPassword  = "******";
            securitySettings.OwnerPassword = "******";
            securitySettings.PermitAccessibilityExtractContent = false;
            securitySettings.PermitAnnotations      = false;
            securitySettings.PermitAssembleDocument = false;
            securitySettings.PermitExtractContent   = false;
            securitySettings.PermitFormsFill        = true;
            securitySettings.PermitFullQualityPrint = false;
            securitySettings.PermitModifyDocument   = true;
            securitySettings.PermitPrint            = true;

            document.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + NameUntis + "-Kennwort.pdf");

            var beginn = (from g in Global.ApaUhrzeiten where g.Key == this.NameUntis select g.Value).FirstOrDefault();

            Excelzeile excelzeile = new Excelzeile();

            excelzeile.ADatum  = Global.Zulassungskonferenz;
            excelzeile.BTag    = string.Format("{0:ddd}", beginn) + " " + beginn.ToString("dd.MM.yyyy");
            excelzeile.CVonBis = new List <DateTime>()
            {
                beginn, beginn.AddMinutes(10)
            };
            excelzeile.DBeschreibung = "Zulassungskonferenz - <a title='Nachricht für " + Global.GetAnrede((this).Klassenleitungen[0]) + "' href='mailto: " + (this).Klassenleitungen[0].Mail + " ?subject=Nachricht für " + Global.GetAnrede((this).Klassenleitungen[0]) + "'>" + "<b>" + (this).NameUntis + "</b></a> - " + this.Beschreibung;
            excelzeile.EJahrgang     = "";
            excelzeile.FBeginn       = beginn;
            excelzeile.GEnde         = beginn.AddMinutes(10);
            excelzeile.HRaum         = new Raums();
            excelzeile.HRaum.Add(new Raum(Global.RaumApa));
            excelzeile.IVerantwortlich = teilnehmer;
            excelzeile.JKategorie      = new List <string>()
            {
                "ZulassungskonferenzBC "
            };
            excelzeile.KHinweise  = "";
            excelzeile.LGeschützt = "";
            excelzeile.Subject    = "Zulassungskonferenz " + NameUntis;

            Global.MailSenden(
                this,
                (from l in lehrers where l.Kürzel == this.Bereichsleitung select l).FirstOrDefault(),
                "Notenliste " + NameUntis + " für " + kla,
                @"Guten Morgen " + kla + @"<br><br>
zur Vorbereitung auf die Zulassungskonferenz der Klasse " + NameUntis + @" am " + string.Format("{0:ddd}", beginn) + " " + beginn.ToString("dd.MM.yyyy") + @" im Raum " + Global.RaumApa + @" erhalten Sie die Liste der Noten Ihrer Klasse.
<br>
<br>
Es werden Ihnen in der Liste alle Fächer angezeigt, die seit dem Schuljahresbeginn unterrichtet wurden. Das schließt auch diejenigen Fächer ein, die z.B. in der zweiten Woche nach den Ferien ersatzlos gestrichen wurden. Als Klassenleitung wissen Sie, wo entsprechend keine Noten erforderlich sind und wo noch Noten fehlen.  
<br>
<br>
Fächer, die von mehreren Lehrkräften unterrichtet werden, werden auch mehrfach aufgeführt. Es kann wahlweise die Eintragung nur von einer Lehrkraft vorgenommen worden sein oder es muss bei allen Lehrkräften dieselbe Noten eingetragen worden sein.
<br><br>
Aus Datenschutzgründen kann die Liste natürlich nicht unverschlüsselt gesendet werden. Das Kennwort ist unsere leicht abgewandelte Schulnummer. Sie finden das Kennwort <a href='https://bk-borken.lms.schulon.org/course/view.php?id=415'>hier</a>. <br><br>Frohe Ostern!<br><br>Stefan Bäumer<br><br>PS: Weil diese Mail samt Inhalt automatisch erstellt und versandt wurde, ist der (angekündigte) Versand der Liste über den Messenger so nicht möglich.", new List <string>()
            {
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + NameUntis + "-Kennwort.pdf"
            });

            File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + NameUntis + ".zip");
            //File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + NameUntis + ".pdf");
            File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + NameUntis + "-Kennwort.pdf");
            Console.WriteLine(" ok");
            return(excelzeile);
        }