Open pdf in windows forms

Отображение файла PDF из Winform

22 gsvirdi [2010-02-08 10:34:00]

Я просто создаю простой калькулятор в С# (форма окна)

Я создал «User Help», который является pdf файлом, и я хочу отобразить этот pdf файл, если пользователь нажимает кнопку «Справка» в WinForm. Если предположить, что Adobe Reader предварительно установлен на пользовательском компьютере.

Как открыть файл pdf при нажатии кнопки в winForm?

Я не планирую предоставить этот pdf файл на жестком диске пользователя. Это означает, что мне нужно встроить этот pdf файл в калькулятор (winForm) и отобразить его при нажатии кнопки.

Прошу вас посоветоваться с лучшей практикой для отображения встроенного файла в winForm.

11 ответов

5 Решение Oliver [2010-02-08 11:11:00]

Я бы включил его в свою папку с программой, добавлю ссылку в свою папку «Пуск», чтобы разрешить прямой доступ (без запуска моего инструмента) и просто на некоторое событие click System.Diagnostics.Process.Start(@».\Manual.pdf»);

Update

Хорошо, теперь мы переходим к совершенно новому вопросу: как вставить файл в мое приложение и запустить его?

Для этого вопроса вы найдете здесь несколько ответов, но вот короткая версия:

  • Щелкните правой кнопкой мыши свой проект и выберите «Добавить» — существующий элемент
  • Выберите свой файл (не дважды щелкните его).
    • Нажмите маленькую стрелку рядом с кнопкой Добавить и выберите Добавить как ссылку
  • Дважды щелкните по Properties — Resources.resx
  • Нажмите маленькую стрелку рядом с надписью «Добавить ресурс» и выберите «Добавить существующий файл»
  • В открывшемся диалоговом окне снова выберите тот же файл
  • Теперь вы можете получить доступ к файлу в своем коде как byte[] из Properties.Resources.NameOfResource

С помощью этих шагов вы ссылаетесь на свой файл, где бы он ни находился в вашей структуре. Если вам нравится, копия вашего pdf файла будет помещена в подпапку Resources в вашем проекте, просто пропустите точки один и два в приведенном выше списке.

Чтобы открыть pdf файл, вам придется записать байт [] на диск (возможно, с Path.GetTempFileName() ) и запустить его с помощью Adobe Reader. (Не забудьте удалить файл после использования)

Вы можете ссылаться на элемент управления Adobe Reader ActiveX и связывать его с вашим приложением.

Просто добавьте AcroPDF.PDF.1 в панель инструментов на вкладке COM Components (панель инструментов правой кнопки мыши и нажмите Choose Items. ), а затем перетащите экземпляр на свою Winform, чтобы дизайнер создал код для вас. Кроме того, после добавления нужной ссылки вы можете использовать следующий код:

Вы можете использовать элемент управления WebBrowser и позволить IE загружать PDF-ридер для вас, если он установлен на компьютере.

Однако в последний раз, когда я это пробовал, мне сначала пришлось записать файл PDF на диск, поэтому я мог бы указать на него элемент управления WebBrowser.

5 Scott Net [2015-12-14 18:54:00]

Если вы хотите отобразить pdf файл в своем приложении, элемент управления WebBrowser, вероятно, предпочтительнее, чем элемент управления Adobe Reader, поскольку он будет очень легко открывать файл в PDF-Reader или независимо от того, что IE использует по умолчанию для открытия PDF файлов. Вы просто добавляете элемент управления WebBrowser в существующую или новую форму и переходите к файлу pdf.

Никогда не предполагайте, что у пользователя есть Adobe или любые другие элементы управления или библиотеки третьих сторон, установленные на их компьютерах, всегда упаковывайте их в свой исполняемый файл или у вас могут быть проблемы.

Управление Adobe Reader, очевидно, также не интегрируется с .NET как внутренним компонентом Windows. Как правило, я всегда предпочитаю использовать встроенные средства .Net для сторонних поставщиков. Что касается вложения файла в фактический исполняемый файл; не произойдет, пока Microsoft не решит, что какой-либо старый PDF файл может быть обработан в CLS и скомпилирован в MSIL. То, что у вас есть при разработке любого приложения в .NET, — это код, который может быть скомпилирован в промежуточную MSIL для перевода в среде выполнения CLR в собственный код и выполнен в ОС.

Читайте также:  Не грузится linux fstab

5 Tommy [2010-02-09 21:29:00]

Если у вашего пользователя есть Adobe Reader (или любой другой PDF-ридер), установленный на их машине, вы можете использовать:

Надеюсь, что это поможет.

Примечание. Очевидно, что это не сработает, если у пользователя нет приложений PDF Reader.

5 cferbs [2010-09-03 16:19:00]

В коде google есть проект С# pdf viewer. http://code.google.com/p/pdfviewer-win32/ есть зритель, и есть библиотека, которую он использует, которая использует mupdf и xpdf для рендеринга pdf-документов в вашей программе winforms. В настоящее время я разрабатываю библиотеку пользовательского управления для людей, которые могут использовать и переходить в свои программы для просмотра PDF файлов. он работает очень хорошо.

4 Snake [2010-02-08 10:35:00]

Я бы предложил преобразовать ваш pdf файл в файл справки Microsoft, чтобы вам не нужно было устанавливать Adobe Reader (это ошибка и слишком много проблем с безопасностью). Вы не можете ожидать от пользователей этого.

В ответ на комментарий стартера:

Да, вам нужно будет создать файл справки как документ HTML вместо pdf. Нет простого способа конвертировать PDF в HTML.

Возможно, вы сможете встроить Adobe Reader в свою форму в качестве компонента ActiveX. Но это означает, что вам нужно будет убедиться, что Reader установлен на клиентской машине для работы.

В случае, если он не должен быть строго встроен, вы можете просто запустить PDF файл и позволить любому зрителю открыть его.

Получение встроенного файла не должно быть проблемой. Это не зависит от того, является ли он форматом .pdf, и вы можете просто искать там отдельное решение.

Для отображения, если вы не знаете, Acrobat или аналогичный установлен (ну, даже Edge может открыть эти файлы в настоящее время), или если вы хотите отобразить файл, встроенный в приложение WinForms, есть

написан на VB, полагаясь на множество (частично коммерческих, если ваше решение является коммерческим) библиотек.

PdfiumViewer

отлично, а также доступен через NuGet.

Это многофункциональное решение для отображения и поставляется с более дружественной лицензией Apache 2.0.

Как открыть файл PDF с относительным путем

В этом случае созданное приложение должно запускаться на нескольких ПК. Чтобы ссылаться на файл, который отсутствует в сети, но в самой папке Programm, используйте следующий фрагмент кода:

Прежде всего, включите следующую библиотеку:

Затем используйте Кнопка, picturebox или для создания ClickEvent и используйте следующий фрагмент кода:

Displaying a pdf file from Winform

I’m just creating a simple calculator in C# (windows form)

I’ve created a «User Help» which is a pdf file, what I want is to display that pdf file if the user clicks on the «Help» button in the WinForm. If assumed that Adobe reader is pre-installed on the user’s machine.

How to open the pdf file on button click in winForm?

I don’t plan to provide this pdf file on hard disk of user. Which means that I have to embed this pdf into the calculator (winForm) and have to display it on the button click.

Kindly guide me with the best practise for displaying an embedded file in winForm.

11 Answers 11

I would put it on within my program folder, add a link within my Start Menu folder to allow a direct access (without starting my tool) and just at on some click event System.Diagnostics.Process.Start(@».\Manual.pdf»);

Update

Ok, now we come to a completely new question: How to embed a file in my application and start it?

For this question you’ll find already several answers here, but here is the short version:

  1. Right click your project and select Add — Existing Item
  2. Select your file (don’t double click it)
    • Click the little arrow next to the Add button and select Add As Link
  3. Double click on Properties — Resources.resx
  4. Click the little arrow next to Add Resource and select Add Existing File
  5. Select the same file again in the open dialog
  6. Now you can access the file within your code as byte[] from Properties.Resources.NameOfResource

With these steps you reference your file where ever it exists within your structure. If you like that a copy of your pdf file will be put into a subfolder Resources within your project, just skip the points one and two in the above list.

Читайте также:  Флешка отформатирована mac os

Как открыть файлы с помощью OpenFileDialog How to: Open files with the OpenFileDialog

System.Windows.Forms.OpenFileDialogКомпонент открывает диалоговое окно Windows для обзора и выбора файлов. The System.Windows.Forms.OpenFileDialog component opens the Windows dialog box for browsing and selecting files. Чтобы открыть и прочитать выбранные файлы, можно использовать OpenFileDialog.OpenFile метод или создать экземпляр System.IO.StreamReader класса. To open and read the selected files, you can use the OpenFileDialog.OpenFile method, or create an instance of the System.IO.StreamReader class. В следующих примерах показаны оба подхода. The following examples show both approaches.

В .NET Framework для получения или задания FileName свойства требуется уровень привилегий, предоставляемый System.Security.Permissions.FileIOPermission классом. In .NET Framework, to get or set the FileName property requires a privilege level granted by the System.Security.Permissions.FileIOPermission class. В примерах выполняется FileIOPermission Проверка разрешений и может вызываться исключение из-за недостаточных привилегий при выполнении в контексте частичного доверия. The examples run a FileIOPermission permission check, and can throw an exception due to insufficient privileges if run in a partial-trust context. Дополнительные сведения см. в статье основы управления доступом для кода. For more information, see Code access security basics.

Вы можете собрать и запустить эти примеры как .NET Framework приложения из командной строки C# или Visual Basic. You can build and run these examples as .NET Framework apps from the C# or Visual Basic command line. Дополнительные сведения см. в разделе Построение из командной строки с помощью csc.exe или Сборка из командной строки. For more information, see Command-line building with csc.exe or Build from the command line.

Начиная с .NET Core 3,0, можно также создавать и запускать примеры как приложения Windows .NET Core из папки с файлом проекта .NET Core Windows Forms . csproj . Starting with .NET Core 3.0, you can also build and run the examples as Windows .NET Core apps from a folder that has a .NET Core Windows Forms .csproj project file.

Пример. чтение файла в виде потока с помощью StreamReader Example: Read a file as a stream with StreamReader

В следующем примере используется Button обработчик событий Windows Forms элемента управления Click для открытия OpenFileDialog с помощью ShowDialog метода. The following example uses the Windows Forms Button control’s Click event handler to open the OpenFileDialog with the ShowDialog method. После того как пользователь выберет файл и нажмет кнопку ОК, экземпляр StreamReader класса считывает файл и отображает его содержимое в текстовом поле формы. After the user chooses a file and selects OK, an instance of the StreamReader class reads the file and displays its contents in the form’s text box. Дополнительные сведения о чтении из файловых потоков см FileStream.BeginRead . в разделе и FileStream.Read . For more information about reading from file streams, see FileStream.BeginRead and FileStream.Read.

Пример. Открытие файла из отфильтрованного выделенного фрагмента с помощью OpenFile Example: Open a file from a filtered selection with OpenFile

В следующем примере Button обработчик событий элемента управления используется Click для открытия OpenFileDialog с фильтром, который отображает только текстовые файлы. The following example uses the Button control’s Click event handler to open the OpenFileDialog with a filter that shows only text files. После того как пользователь выберет текстовый файл и нажмет кнопку ОК, OpenFile для открытия файла в блокноте используется метод. After the user chooses a text file and selects OK, the OpenFile method is used to open the file in Notepad.

5 Most Popular PDF Form Filler in 2021

Elise Williams

2021-03-10 20:31:28 • Filed to: Top List of PDF Software • Proven solutions

There are several free PDF form fillers on the market. Recently, more sophisticated PDF form filling software has become available that can do much more than just fill a form. Due to the number of free form filling platforms found both online and offline, users have a ton of options when it comes to finding free PDF form fillers. In this article, we’ll highlight the top 5 currently on the market.

5 Best Free PDF Filler

1. PDFelement

The ease-to-use functions associated with this particular PDF form filler have made PDFelement a recognized and respected program. You can download its free trial version to fill forms.

Читайте также:  Mount network share windows

PDFelement allows you to create and fill PDF forms. It also has integrated features from other free PDF form fillers to allow for easy sharing and printing of forms. You can save your form to your device for future use and printing purposes. Also, PDFelement provides features that let you edit, sign, and perform OCR on PDF forms.

It is fully compatible with all Windows systems, from Windows XP to Windows 10. Download the free trial version of this professional PDF form filler to try it out! If you are a Mac user, try PDFelement. It is compatible with the latest macOS Catalina 10.15. This video shows how to fill out a PDF form, providing you with a more direct and detailed guide, and you can also explore more videos from Wondershare Video Community.

Best Free PDF Form Filler — PDFelement

Scenario 1. Fill PDF Forms with Interactive Fields

PDFelement lets you easily fill a PDF form with interactive fields. After you download and install the PDF form filler software, launch the program. Click the «Open File» button to browse your computer or drag and drop the PDF into the program window. The form filler software will detect all of the interactive fields automatically once the file is open. Now you start directly typing in the fields or selecting the right responses from the options provided.

Scenario 2. Fill Non-Interactive PDF Forms

Not all PDF forms have interactive fields. Some forms are created from different types such as Microsoft Excel, Word, or plain text and covered to PDF. To fill one of these types of converted PDF forms, open it with PDFelement, then go to the «Form» tab and click on «Form Recognition.» It will automatically detect where the fields should be. You can then click the «Close Form Editing» button and start filling in the field like you would with interactive PDF forms.

Now you know how to fill in a PDF form with or without interactive fields using PDFelement. After filling out the PDF form, you can save the completed PDF form by clicking the «Save» icon in the top left-hand corner of the main interface. As one of the best PDF Form Fillers on the market, PDFelement also lets you add a handwritten or electronic signature to your PDF form as well.

Recommendations of Other PDF Form Filler

1. Adobe В® Acrobat В®

Adobe Acrobat is a PDF tool that allows the user to edit, fill, and read PDF forms. It offers advanced form filling techniques and provides the most extensive features for creating PDF forms as well. However, Acrobat XI has ended all support, meaning there will be no more security updates, product updates, or customer support. In this case, you can click here to find out the best alternatives to Adobe Acrobat.

2. PDFill

PDfill form filler has been integrated with top-notch functions and tools. From the PDfill form filler window page, the user is able to select the form format and select the editing fonts types, font color, and font size. This particular PDF form filler allows the user to be able to import and export filled forms and data to be filled in the editable fields.

3. Blueberry PDF Form Filler

Blueberry PDF Form Filler is free software that enables the user to fill and print PDF forms. It has enhanced functions that are on par with Adobe Reader filling capabilities. You can open your document in the program, and then fill in the data through selecting the appropriate fields. In the process, the filler converts the fields into editable fields that can be filled with data. This program provides several fonts and text sizes that conform to other text in the document as well.

4. PDF Buddy

PDF Buddy is an online platform that allows for editing and general form filling to your online hosted document. This particular PDF form filler gives you the ability to work anywhere, saves time, and is free to use. Plus, it is easy to enhance your PDF files.

Оцените статью