mardi 21 février 2023

Delete a page from a PDF using C#

 public void DeletePDFPage(string sourcePath, string outputPath, int pageNumber)

{

    using (PdfReader reader = new PdfReader(sourcePath))

    {

        int pageCount = reader.NumberOfPages;


        if (pageNumber < 1 || pageNumber > pageCount)

        {

            throw new ArgumentException("Invalid page number");

        }


        using (PdfStamper stamper = new PdfStamper(reader, new FileStream(outputPath, FileMode.Create)))

        {

            stamper.Writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);


            for (int i = pageCount; i >= 1; i--)

            {

                if (i == pageNumber)

                {

                    continue;

                }


                PdfDictionary pageDict = reader.GetPageN(i);

                int rotate = pageDict.GetAsNumber(PdfName.ROTATE)?.IntValue ?? 0;

                Rectangle pageSize = reader.GetPageSizeWithRotation(i);


                PdfImportedPage importedPage = stamper.GetImportedPage(reader, i);

                PdfContentByte content = stamper.GetUnderContent(i);


                content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);


                PdfCopy.PageStamp pageStamp = stamper.CreatePageStamp(importedPage);

                pageStamp.AlterContents();

                stamper.AddPage(importedPage, new Rectangle(pageSize.Width, pageSize.Height, rotate));

                stamper.AlterContents(pageCount - i + 1, pageStamp.GetOverContent());

            }

        }

    }

}


Merge pdf files using C#

 public void MergePDFFiles(string[] filepaths, string outputpath)

{

    using (FileStream stream = new FileStream(outputpath, FileMode.Create))

    {

        Document document = new Document();

        PdfCopy pdf = new PdfCopy(document, stream);

        document.Open();


        foreach (string filepath in filepaths)

        {

            using (PdfReader reader = new PdfReader(filepath))

            {

                pdf.AddDocument(reader);

            }

        }


        document.Close();

    }

}


C# function to minimize image size

 public void MinimizeImageSize(string sourcePath, string outputPath, int maxWidth, int maxHeight, long quality)

{

    using (Image sourceImage = Image.FromFile(sourcePath))

    {

        int width = sourceImage.Width;

        int height = sourceImage.Height;


        // Scale the image to fit within the specified maximum dimensions

        if (width > maxWidth || height > maxHeight)

        {

            if ((double)width / maxWidth > (double)height / maxHeight)

            {

                height = (int)(height * ((double)maxWidth / width));

                width = maxWidth;

            }

            else

            {

                width = (int)(width * ((double)maxHeight / height));

                height = maxHeight;

            }

        }


        // Create a new bitmap with the scaled dimensions

        using (Bitmap outputBitmap = new Bitmap(width, height))

        {

            using (Graphics graphics = Graphics.FromImage(outputBitmap))

            {

                // Set the image quality and compression settings

                EncoderParameters encoderParams = new EncoderParameters(1);

                encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);


                // Draw the scaled image onto the new bitmap

                graphics.CompositingQuality = CompositingQuality.HighQuality;

                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                graphics.SmoothingMode = SmoothingMode.HighQuality;

                graphics.DrawImage(sourceImage, new Rectangle(0, 0, width, height));


                // Save the new image to the specified output path

                outputBitmap.Save(outputPath, GetEncoderInfo("image/jpeg"), encoderParams);

            }

        }

    }

}


private ImageCodecInfo GetEncoderInfo(string mimeType)

{

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

    foreach (ImageCodecInfo codec in codecs)

    {

        if (codec


C# function to download PDF

 public void DownloadPDF(string url, string filename)

{

    using (WebClient client = new WebClient())

    {

        client.DownloadFile(url, filename);

    }

}


Logout User function using c#

public void Logout()

{

    // Remove the current user from the session

    UserSession.CurrentUser = null;

}

 

LOGIN USER FUNCTION C#

 public bool Login(string username, string password)

{

    // Validate username and password

    if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))

    {

        return false;

    }


    // Check if the username and password are valid

    bool isValidUser = ValidateUser(username, password);


    if (isValidUser)

    {

        // Log the user in

        UserSession.CurrentUser = new User(username);

        return true;

    }


    return false;

}


private bool ValidateUser(string username, string password)

{

    // Implement your logic to validate the user's credentials

    // For example, you could check against a database of registered users

    // or call an authentication API


    // In this example, we'll just assume that the username and password are valid

    return true;

}