PDFsharp & MigraDoc Foundation
http://forum.pdfsharp.com/

Can't open PDF file after creation
http://forum.pdfsharp.com/viewtopic.php?f=2&t=4328
Page 1 of 1

Author:  sharpuser90 [ Thu Mar 03, 2022 6:41 pm ]
Post subject:  Can't open PDF file after creation

I am trying to combine two PDF files into one and then open the file in my pdf reader. However, after creating the file I'm not able to open it. I get an error when trying to open the file that the file is already open or in use. This happens whether I prompt it to open programmatically or go to the folder and open it that way. It will not open until my program is closed, and then it opens just fine. I tried adding lines to .Close(), .Dispose(), or set the variable to Nothing, but it doesn't change anything. The file is still in use as long as the program is open. How can I get it to release the file so I can open it? See my code below, thanks.

Code:
        Dim PDF1 As String = "C:\Test\pdf1.pdf"
        Dim PDF2 As String = "C:\Test\pdf2.pdf"
        Dim combinedPDF As String = "C:\Test\combinedpdf.pdf"
        Dim outputDocument As PdfDocument = Nw PdfDocument()

        If File.Exists(PDF1) Then
            Dim inputDocument As PdfDocument = PdfReader.Open(PDF1, PdfDocumentOpenMode.Import)

            Dim PDFPageCount As Integer = inputDocument.PageCount
            Dim count As Integer = 0
            While count < PDFPageCount
                Dim page As PdfPage = inputDocument.Pages(count)
                outputDocument.AddPage(page)
                count += 1
            End While
        End If

        If File.Exists(PDF2) Then
            Dim inputDocument As PdfDocument = PdfReader.Open(PDF2, PdfDocumentOpenMode.Import)

            Dim PDFPageCount As Integer = inputDocument.PageCount
            Dim count As Integer = 0
            While count < PDFPageCount
                Dim page As PdfPage = inputDocument.Pages(count)
                outputDocument.AddPage(page)
                count += 1
            End While
        End If

        outputDocument.Save(combinedPDF)

        outputDocument.Close()
        outputDocument.Dispose()
        outputDocument = Nothing

        Process.Start(combinedPDF)

Author:  TH-Soft [ Thu Mar 03, 2022 6:51 pm ]
Post subject:  Re: Can't open PDF file after creation

We don't have this issue with our C# or VB samples.
See also:
http://forum.pdfsharp.net/viewtopic.php?f=2&t=832

You can use PdfDocument.Save() to write the PDF into a MemoryStream and then handle all the file IO in your own code.

Author:  sharpuser90 [ Thu Mar 03, 2022 10:00 pm ]
Post subject:  Re: Can't open PDF file after creation

I'm not sure why my code wasn't working, but thank you for pointing out the stream option, that route seems to have done the trick without locking down the file.

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/