Jump to content

C# - Issue with Saving Images to PDF

Go to solution Solved by AbydosOne,
10 minutes ago, WelshDdraig said:

but when I go to save the document with a SaveFileDialog, the document doesn't save.

Stab in the dark here (I speak Java a lot more fluently than C#), but would you need a line to the effect of...

document.save(saveFileDialog1.getSavePath())

... after calling the "saveFileDialog1" in order to complete the operation?

 

Whenever I use save dialogs in Java, they only return a path to a file, and don't do any of the saving work themselves, so that's my line of reasoning.

Hi Everyone, 

 

I haven't done any programming for a while (like upwards of a year to a year and a half or so), and decided to try and make a program to convert a collection of images to a PDF.

The program should work - and I believe it will work, however - I seem to be having an issue when it comes to saving the file.


With my code, I can get the program to run and execute fine, but when I go to save the document with a SaveFileDialog, the document doesn't save.

I could be missing something extremely simple, but cannot seem to be able to figure it out. 

As such, I was hoping people on the forum might be able to help me out.

 

My program's concept was based around this video, but modified by me so I can see the images loaded in a ListBox and preview the image when clicked in a PictureBox (That bit works fine), using code from the link below the video.

It's just the document saving/output I seem to be having. Unlike the example, I do not want to hard code a save path or file name, but use a SaveFileDialog. 
Just as a note, to do the PDF Conversion, I am using the PdfSharp library (like the one used in the video in the spoiler).

Here is my code:

Spoiler

namespace JPGtoPDFConverter
{
    public partial class Form1 : Form
    {
        string parentDir = "";
        PdfDocument document = new PdfDocument();

        public Form1()

        {
            InitializeComponent();
        }

        private void lstBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string filename = System.IO.Path.Combine(parentDir, lstBox1.SelectedItem.ToString());
            pictureBox1.Image = Image.FromFile(filename);
        }

        private void bntOpenFiles_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Filter = "";
                dlg.Title = "";
                dlg.Multiselect = true;

                var images = imageList1.Images;                

                DialogResult dr = dlg.ShowDialog(this);
                if (dr == DialogResult.OK)
                {
                    foreach (string file in dlg.FileNames)
                    {                        
                      lstBox1.Items.Add(file);
                      images.Add(Image.FromFile(file));

                     PdfPage page = document.AddPage();
                     XGraphics gfx = XGraphics.FromPdfPage(page);
                     DrawImage(gfx, file, 0, 0, (int)page.Width, (int)page.Height);

                    }
                }
            }           
        }

        void DrawImage(XGraphics gfx, string file, int x, int y, int width, int height)
        {
            XImage image = XImage.FromFile(file);
            gfx.DrawImage(image, x, y, width, height);
        }

        private void btnGenPDF_Click(object sender, EventArgs e)
        {            

            if (document.PageCount > 0)
            {

                SaveFileDialog saveFileDialog1 = new SaveFileDialog
                {
                    Filter = "PDF File|*.pdf",
                    Title = "Generate PDF"
                };                
            }
        }        
    }     
    
}

 

Thanks for your time and input. This issue is probably me being stupid...

Ryze of the Phoenix: 
CPU:      AMD Ryzen 5 3600 @ 4.15GHz
Ram:      64GB Corsair Vengeance LPX DDR4 @ 3200Mhz (Samsung B-Die & Nanya Technology)
GPU:      MSI RTX 3060 12GB Aero ITX
Storage: Crucial P3 1TB NVMe Gen 4 SSD, 1TB Crucial MX500, Spinning Rust (7TB Internal, 16TB External - All in-use),
PSU:      Cooler Master MWE Gold 750w V2 PSU (Thanks LTT PSU Tier List)
Cooler:   BeQuite! Prue Rock 2 Black Edition
Case:     ThermalTake Versa J22 TG

Passmark 10 Score: 6096.4         CPU-z Score: 4189 MT         Unigine Valley (DX11 @1080p Ultra): 5145         CryEngine Neon Noir (1080p Ultra): 9579

Audio Setup:                  Scarlett 2i2, AudioTechnica AT2020 XLR, Mackie CR3 Monitors, Sennheiser HD559 headphones, HyperX Cloud II Headset, KZ ES4 IEM (Cyan)

Laptop:                            MacBook Pro 2017 (Intel i5 7360U, 8GB DDR3, 128GB SSD, 2x Thunderbolt 3 Ports - No Touch Bar) Catalina & Boot Camp Win10 Pro

Primary Phone:               Xiaomi Mi 11T Pro 5G 256GB (Snapdragon 888)

Link to comment
Share on other sites

Link to post
Share on other sites

10 minutes ago, WelshDdraig said:

but when I go to save the document with a SaveFileDialog, the document doesn't save.

Stab in the dark here (I speak Java a lot more fluently than C#), but would you need a line to the effect of...

document.save(saveFileDialog1.getSavePath())

... after calling the "saveFileDialog1" in order to complete the operation?

 

Whenever I use save dialogs in Java, they only return a path to a file, and don't do any of the saving work themselves, so that's my line of reasoning.

Main System (Byarlant): Ryzen 7 5800X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 16GB G.Skill DDR4 3200MT/s CAS-14 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 960 PRO 512GB / 4× Crucial MX500 2TB (RAID-0) | Corsair RM750X | a 10G NIC (pending) | Inateck USB 3.0 Card | Hyte Y60 Case | Dell U3415W Monitor | Keychron K4 Brown (white backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB RAM (soldered) | Vega 6 Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi (all-around awesome machine)

 

Proxmox Server (Veda): Ryzen 7 3800XT | AsRock Rack X470D4U | Corsair H80i v2 | 64GB Micron DDR4 ECC 3200MT/s | 4x 10TB WD Whites / 4x 14TB Seagate Exos / 2× Samsung PM963a 960GB SSD | Seasonic Prime Fanless 500W | Intel X540-T2 10G NIC | LSI 9207-8i HBA | Fractal Design Node 804 Case (side panels swapped to show off drives) | VMs: TrueNAS Scale; Ubuntu Server (PiHole/PiVPN/NGINX?); Windows 10 Pro; Ubuntu Server (Apache/MySQL)


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s CAS-22 | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / TEAMGROUP MS30 1TB | Corsair CX450M | Viewcast Osprey 260e Video Capture | Mellanox ConnectX-2 10G NIC | LG UH12NS30 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Camera: Sony ɑ7II w/ Meike Grip | Sony SEL24240 | Samyang 35mm ƒ/2.8 | Sony SEL50F18F | Sony SEL2870 (kit lens) | PNY Elite Perfomance 512GB SDXC card

 

Network:

Spoiler
                           ┌─────────────── Office/Rack ────────────────────────────────────────────────────────────────────────────┐
Google Fiber Webpass ────── UniFi Security Gateway ─── UniFi Switch 8-60W ─┬─ UniFi Switch Flex XG ═╦═ Veda (Proxmox Virtual Switch)
(500Mbps↑/500Mbps↓)                             UniFi CloudKey Gen2 (PoE) ─┴─ Veda (IPMI)           ╠═ Veda-NAS (HW Passthrough NIC)
╔═══════════════════════════════════════════════════════════════════════════════════════════════════╩═ Narrative (Asus USB 2.5G NIC)
║ ┌────── Closet ──────┐   ┌─────────────── Bedroom ──────────────────────────────────────────────────────┐
╚═ UniFi Switch Flex XG ═╤═ UniFi Switch Flex XG ═╦═ Byarlant
   (PoE)                 │                        ╠═ Narrative (Cable Matters USB-PD 2.5G Ethernet Dongle)
                         │                        ╚═ Jesta Cannon*
                         │ ┌─────────────── Media Center ──────────────────────────────────┐
Notes:                   └─ UniFi Switch 8 ─────────┬─ UniFi Access Point nanoHD (PoE)
═══ is Multi-Gigabit                                ├─ Sony Playstation 4 
─── is Gigabit                                      ├─ Pioneer VSX-S520
* = cable passed to Bedroom from Media Center       ├─ Sony XR65A80K (Google TV)
** = cable passed from Media Center to Bedroom      └─ Work Laptop** (Startech USB-PD Dock)

Retired/Other:

Spoiler

Laptop (Rozen-Zulu): Sony VAIO VPCF13WFX | Core i7-740QM | 8GB Patriot DDR3 | GT 425M | Samsung 850EVO 250GB SSD | Blu-ray Drive | Intel 7260 Wifi (lived a good life, retired with honor)

Testbed/Old Desktop (Kshatriya): Xeon X5470 @ 4.0GHz | ZALMAN CNPS9500 | Gigabyte EP45-UD3L | 8GB Nanya DDR2 400MHz | XFX HD6870 DD | OCZ Vertex 3 Max-IOPS 120GB | Corsair CX430M | HooToo USB 3.0 PCIe Card | Osprey 230 Video Capture | NZXT H230 Case

TrueNAS Server (La Vie en Rose): Xeon E3-1241v3 | Supermicro X10SLL-F | Corsair H60 | 32GB Micron DDR3L ECC 1600MHz | 1x Kingston 16GB SSD / Crucial MX500 500GB

Link to comment
Share on other sites

Link to post
Share on other sites

18 minutes ago, AbydosOne said:

Stab in the dark here (I speak Java a lot more fluently than C#), but would you need a line to the effect of...


document.save(saveFileDialog1.getSavePath())

... after calling the "saveFileDialog1" in order to complete the operation?

 

Whenever I use save dialogs in Java, they only return a path to a file, and don't do any of the saving work themselves, so that's my line of reasoning.

Thanks for the help. 

That didn't solve my issue - however, it made me take a closer look at my code and I can't believe I was so stupid haha.
Turns out - all I did was open the dialog - I didn't have anything coded to save the file. (Time for me to re-read all my C# books...again.

Here's the code I added to fix my issue:

private void btnGenPDF_Click(object sender, EventArgs e)
        {
            if (document.PageCount > 0)
            {
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Title = "Generate PDF";
                    dialog.Filter = "PDF document (*.pdf)|*.pdf";
                    DialogResult result = dialog.ShowDialog();
                    string fileName = dialog.FileName;
                    if (result == DialogResult.OK)
                    {
                        document.Save(fileName);
                    }                   
                }
            }
        }


Thanks again for the suggestion.

Ryze of the Phoenix: 
CPU:      AMD Ryzen 5 3600 @ 4.15GHz
Ram:      64GB Corsair Vengeance LPX DDR4 @ 3200Mhz (Samsung B-Die & Nanya Technology)
GPU:      MSI RTX 3060 12GB Aero ITX
Storage: Crucial P3 1TB NVMe Gen 4 SSD, 1TB Crucial MX500, Spinning Rust (7TB Internal, 16TB External - All in-use),
PSU:      Cooler Master MWE Gold 750w V2 PSU (Thanks LTT PSU Tier List)
Cooler:   BeQuite! Prue Rock 2 Black Edition
Case:     ThermalTake Versa J22 TG

Passmark 10 Score: 6096.4         CPU-z Score: 4189 MT         Unigine Valley (DX11 @1080p Ultra): 5145         CryEngine Neon Noir (1080p Ultra): 9579

Audio Setup:                  Scarlett 2i2, AudioTechnica AT2020 XLR, Mackie CR3 Monitors, Sennheiser HD559 headphones, HyperX Cloud II Headset, KZ ES4 IEM (Cyan)

Laptop:                            MacBook Pro 2017 (Intel i5 7360U, 8GB DDR3, 128GB SSD, 2x Thunderbolt 3 Ports - No Touch Bar) Catalina & Boot Camp Win10 Pro

Primary Phone:               Xiaomi Mi 11T Pro 5G 256GB (Snapdragon 888)

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×