Прескочи на основното съдържание

Как да запишете всяка страница като отделни pdf файлове в Word документ?

Автор: Силувия Последна промяна: 2020-05-28

Докато използвате документ на Microsoft Word, можете да запишете всяка страница като отделни pdf файлове един по един с вградената функция Save As. Но ако има стотици страници, които трябва да бъдат разделени и запазени като отделни pdf файлове, как можете да го направите? Тази статия предоставя метод за бързо решаване на този проблем.

Запазете всяка страница като отделни pdf файлове групово с VBA код


Запазете всяка страница като отделни pdf файлове групово с VBA код

Кодът VBA по-долу ви помага бързо да запазите всяка страница в документ като отделни pdf файлове едновременно. Моля, направете следното.

1. Отворете документа, който ще запишете всяка страница или конкретни страници като pdf файлове, след което натиснете Друг + F11 за да отворите Microsoft Visual Basic за приложения прозорец.

2. В Microsoft Visual Basic за приложения прозорец, кликнете Поставете > Модул, копирайте под VBA кода в прозореца на модула.

VBA код: Запазете всяка страница като отделни pdf файлове едновременно в Word документ

Sub SaveAsSeparatePDFs()
'Updated by Extendoffice 20180906
    Dim I As Long
    Dim xStr As String
    Dim xPathStr As Variant
    Dim xDictoryStr As String
    Dim xFileDlg As FileDialog
    Dim xStartPage, xEndPage As Long
    Dim xStartPageStr, xEndPageStr As String
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    If xFileDlg.Show <> -1 Then
        MsgBox "Please chose a valid directory", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    xPathStr = xFileDlg.SelectedItems(1)
    xStartPageStr = InputBox("Begin saving PDFs starting with page __? " & vbNewLine & "(ex: 1)", "Kutools for Word")
    xEndPageStr = InputBox("Save PDFs until page __?" & vbNewLine & "(ex: 7)", "Kutools for Word")
    If Not (IsNumeric(xStartPageStr) And IsNumeric(xEndPageStr)) Then
        MsgBox "The enterng start page and end page should be number format", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    xStartPage = CInt(xStartPageStr)
    xEndPage = CInt(xEndPageStr)
    If xStartPage > xEndPage Then
        MsgBox "The start page number can't be larger than end page", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    If xEndPage > ActiveDocument.BuiltInDocumentProperties(wdPropertyPages) Then
        xEndPage = ActiveDocument.BuiltInDocumentProperties(wdPropertyPages)
    End If
    For I = xStartPage To xEndPage
        ActiveDocument.ExportAsFixedFormat xPathStr & "\Page_" & I & ".pdf", _
        wdExportFormatPDF, False, wdExportOptimizeForPrint, wdExportFromTo, I, I, wdExportDocumentWithMarkup, _
        False, False, wdExportCreateHeadingBookmarks, True, False, False
    Next
End Sub

3. Натисни F5 ключ за изпълнение на кода.

4. В паса прозорец, изберете папка за запазване на pdf файловете и щракнете върху OK бутон. Вижте екранна снимка:

5. В първия Kutools за Word диалогов прозорец, въведете номера на началната страница на вашия документ в текстовото поле и щракнете OK.

6. Във втория Kutools за Word диалогов прозорец, въведете номера на последната страница на вашия документ, след което щракнете OK. Вижте екранна снимка:

Забележка: Ако просто искате да запазите няколко последователни страници в документа като отделни pdf файлове, като например страница 4, 5 и 6, моля, въведете 4 и 6 отделно в горните два диалогови прозореца.

След като стартирате кода, моля, отидете в посочената папка, която сте избрали в стъпка 4, можете да видите, че всички страници са разделени и запазени като отделни pdf файлове, както е показано на екранната снимка по-долу.


Разделете и запазете всяка страница от документ като отделни нови документи:

- Разделен документ полезност на Kutools за Excel може да ви помогне лесно да разделите и запазите всяка страница от текущия документ като отделен нов документ в насипно състояние, както е показано на екранната снимка по-долу. Изтеглете и опитайте сега! (60-дневна безплатна пътека)

Най-добрите инструменти за продуктивност в офиса

Kutools за Word - Подобрете своя Word опит с Over 100 Забележителни функции!

🤖 Kutools AI Assistant: Преобразувайте писането си с AI - Генериране на съдържание  /  Пренаписване на текст  /  Обобщаване на документи  /  Запитване за информация въз основа на Документ, всичко това в Word

📘 Владеене на документи: Разделяне на страници  /  Обединяване на документи  /  Експортиране на селекция в различни формати (PDF/TXT/DOC/HTML...)  /  Пакетно конвертиране в PDF  /  Експортиране на страници като изображения  /  Отпечатайте няколко файла наведнъж...

Редактиране на съдържанието: Пакетно намиране и замяна в множество файлове  /  Преоразмеряване на всички снимки  /  Транспониране на редовете и колоните на таблицата  /  Преобразуване на таблица в текст...

🧹 Почистване без усилие: Изметете Допълнителни пространства  /  Прекъсвания на раздели  /  Всички заглавки  /  Текстови полета  /  Хипервръзки  / За повече инструменти за премахване се насочете към нашия Премахване на група...

Творчески вложки: Вмъкване Хилядни разделители  /  Квадратчета  /  Радио бутони  /  QR Code  /  Баркод  /  Таблица с диагонални линии  /  Надпис на уравнение  /  Надпис на изображението  /  Надпис на таблица  /  Множество снимки  / Открийте повече в Вмъкване на група...

🔍 Прецизни селекции: Точна точка конкретни страници  /  таблици  /  форми  /  заглавни параграфи  / Подобрете навигацията с още Изберете функции...

Звездни подобрения: Навигирайте бързо до всяко място  /  автоматично вмъкване на повтарящ се текст  /  безпроблемно превключване между прозорците на документи  /  11 Инструменти за конвертиране...

👉 Искате ли да изпробвате тези функции? Kutools за Word предлага a 60-дневен безплатен пробен период, без ограничения! ????
 
Comments (26)
Rated 5 out of 5 · 3 ratings
This comment was minimized by the moderator on the site
How to set output File Name base on footer each page?
This comment was minimized by the moderator on the site
Hello,

I was wondering if there was a way to have it pull the name for the PDF from the word doc. Example: instead of Page_01, have a pull an account number that was the 3rd line down in the word document?
This comment was minimized by the moderator on the site
Hi
what if I need to set specific name for each splited PDF.
This should be taken from WORD text - it is serial korespondece- all pages have same format
Can you advise?
This comment was minimized by the moderator on the site
Hi, how would you save each pdf page as a name that can be found from within each word page being exported?
This comment was minimized by the moderator on the site
Hi, how will change the code for mac os?
This comment was minimized by the moderator on the site
Is there a way to save per 2 pages?

Ex. save page 1/2 in Page_1.pdf
save page 3/4 in Page_2.pdf

Thanks!
This comment was minimized by the moderator on the site
im wondering the same thing! please help!
This comment was minimized by the moderator on the site
Wondering the same
This comment was minimized by the moderator on the site
10x :) this was realy helpful!!!
Rated 5 out of 5
This comment was minimized by the moderator on the site
Thanks for this, this is great. i was wondering if you have a way of naming my pdf files differently per each extract not only Page_1.pdf.

Thanks
This comment was minimized by the moderator on the site
Hi samir,
How would you like to name these pdf files? Please give me an example.
This comment was minimized by the moderator on the site
Like saving each document with a different name, not just Page_1.pdf and so on.
This comment was minimized by the moderator on the site
Hi Camila,
The following VBA code can help you solve the problem.
Note: You need to specify a different name in this line: xFileName = "AA; BB; CC; DD". Here AA, BB and CC are the names for the PDF files.
Please change them to meet your needs. You can add more names and separate them by semicolon. To mention that the number of names specified must match the number of pages you expored. And the PDF files will be named in order of the specified names in the code.
Sub SaveAsSeparatePDFs()
'Updated by Extendoffice 20221223
    Dim xStr As String
    Dim xPathStr As Variant
    Dim xDictoryStr As String
    Dim xFileDlg As FileDialog
    Dim xStartPage, xEndPage As Long
    Dim xStartPageStr, xEndPageStr As String
    Dim xFileName As String
    Dim xNameArr() As String

    xFileName = "AA; BB; CC; DD"  'Specify a name for each page. The number of names specified must match the number of pages you exported.The PDF files will be named in order of the the specified names
    xNameArr = VBA.Split(xFileName, ";")
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    If xFileDlg.Show <> -1 Then
        MsgBox "Please chose a valid directory", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    xPathStr = xFileDlg.SelectedItems(1)
    xStartPageStr = InputBox("Begin saving PDFs starting with page __? " & vbNewLine & "(ex: 1)", "Kutools for Word")
    xEndPageStr = InputBox("Save PDFs until page __?" & vbNewLine & "(ex: 7)", "Kutools for Word")
    If Not (IsNumeric(xStartPageStr) And IsNumeric(xEndPageStr)) Then
        MsgBox "The enterng start page and end page should be number format", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    xStartPage = CInt(xStartPageStr)
    xEndPage = CInt(xEndPageStr)
    If xStartPage > xEndPage Then
        MsgBox "The start page number can't be larger than end page", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    If xEndPage > ActiveDocument.BuiltInDocumentProperties(wdPropertyPages) Then
        xEndPage = ActiveDocument.BuiltInDocumentProperties(wdPropertyPages)
    End If
    For I = xStartPage To xEndPage
        ActiveDocument.ExportAsFixedFormat xPathStr & "\" & VBA.Trim(xNameArr(I - 1)) & ".pdf", _
        wdExportFormatPDF, False, wdExportOptimizeForPrint, wdExportFromTo, I, I, wdExportDocumentWithMarkup, _
        False, False, wdExportCreateHeadingBookmarks, True, False, False
    Next
    Erase xNameArr
End Sub
This comment was minimized by the moderator on the site
Добрый день!
Есть ли возможность сохранить из ворд файла(используя слияние) в пдф файл - Решения собственников на общее собрание.
При этом учитываем, что PDF должен сохраняться так: в 1 файле должно быть несколько листов (1 квартира), по данному модулю страницы сохраняются в пдф, но раздельно
This comment was minimized by the moderator on the site
Hi,
Sorry I don't understand what you mean. You may need to attach a screenshot or a sample file to describe the problem you encountered more clearly.
This comment was minimized by the moderator on the site
Thanks for the script, it has also saved me a lot of work in exporting pages as pdf!
Rated 5 out of 5
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations