Jdi na obsah Jdi na menu
 


PDF thumbnails from VBA

I was asked to develop a form where user can see a pdf thumbnail of a pdf file. It was pretty far from what I have been developing so I decided to use "uncle" google to find a solution. There are some solutions but nothing what was expecting. You can use paid version of Adobe or free Adobe Acrobat ActiveX (Acropdf1) or some others free tools that can work along a pdf file. I tested only the free version of Acrobat ActiveX component and it was really nightmare. Then I found a C# project using the GhostScript tool for creating a pdf thumbnail. Unfortunatelly VBA cannot work with this project directly. Read more to find solution.

As I mentioned you can use the Acropdf1 activeX which is automatically installed with the Adobe Reader application.

Acropdf1.PNG, 35kB

How to add the Acropdf1 activeX on a VBA form

At the first time the activeX seemed to be a good solution but then I found two "bugs". The first one is more important than the second one. The activeX takes focus and never give it back and if you press the "TAB" key, then the whole application will crash. It's very known bug but Adobe cannot fix it for some reason. And the second bug rather behavior - of the activeX control is uncomfortable - it always takes focus and never give it back and also you don't have option to find out if a pdf document is fully loaded or not. My client was complaining about that for many times so I decided to find another solution.

I found code from Matthew Ephraim. where he uses a free tool Ghostscrip and .NETFramework 3.5 and C#. Form Visual Studio you can use his tool without any problems just include it into your project. Unfortunately we cannot use his dll directly from VBA. That was the reason why I took his code and made a little adjustment to expose methods from his project to the COM object.
Now - after registration the dll to your system - you can reference the dll as usually and use it !!! And it works great.

GhostScriptSharp_reference.PNG, 17kB

Who is interested how to create a C# dll that can work with VBA I attached the zip file with entire C# solution. Look at the Attachment section.
And who just want to use it as soon as possible, download the installer and install it. I also prepare a sample and you can find everything in the Attachment section.
The installer just check if your system contains the .NETFramework 4 and if not, it will suggest to download it and then register the dlls into your system.

Your code can look like this one
and then you can take the output file as an ordinary image file and load it - for example - to an image control.

Option Explicit
'********************************************************************************
'TestPDFThumbnailGeneration
'
' Purpose:  It uses reference to GhostscriptWrapper library.
'           From a pdf file creates a jpg file that represents a thumbnail of the pdf.
'           You can set page number and DPI quality.
'
' Inputs:   -none-
'
' Outputs:  -none-
'
' Created:  02/10/2011  Premysl Lazecky
'
' Modified: .
'
'********************************************************************************
Sub TestPDFThumbnailGeneration()

    Dim PDF             As GhostscriptWrapper
    Dim strPath         As String
    Dim strInputFile    As String
    
    strInputFile = "Test.pdf"
    strPath = ActiveWorkbook.Path
    If Right$(strPath, 1) <> Application.PathSeparator Then
       strPath = strPath & Application.PathSeparator
    End If
    
    Set PDF = New GhostscriptWrapper
    
    PDF.GeneratePDFThumb inputPath:=strPath & strInputFile, _
                         outputPath:=strPath & "Output.jpg", _
                         Page:=1, _
                         Width:=72, Height:=72
    
        
    Set PDF = Nothing
        
End Sub

 As the result of this code you will get a jpg file called Output.jpg  with thumbnail of defined page in the pdf file - in this case page 1 - with defined resolution.

Attachments

Installer and sample files
C# project

 

 

Komentáře

Přidat komentář

Přehled komentářů

XRumer 19.0 + XEvil break more than 8400 type of CAPTCHAs

(NatashaKnini4504, 11. 8. 2020 4:11)

Absolutně nová aktualizace balíčku SEO / SMM "XRumer 19.0 + XEvil 5.0":
captcha řešení Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
a více než 12000 dalších kategorií captcha,
s nejvyšší přesností (80 až 100%) a nejvyšší rychlostí (100 img za sekundu).
Můžete připojit XEvil 5.0 k nejoblíbenějšímu softwaru SEO / SMM: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke a více než 100 dalších softwarů.

Zájem? Existuje spousta nepřehledných videí o XEvile na YouTube.
Hodně štěstí!

Are you 18? Come in and don't be shy!

(AllenBrese, 7. 7. 2020 17:00)

Hurry up to look into loveawake.ru you will find a lot of interesting things

Приветствую Вас

(petcom, 23. 6. 2020 20:10)

Не удалось дозвониться, вот мой телефон. 8(903)749-86-80 Константин

Hi! Only from 18+!

(SandraRip, 3. 6. 2020 11:55)

Hurry up to look into loveawake.ru you will find a lot of interesting things....

Map distribution coronavirus

(Thomasoscip, 30. 5. 2020 11:30)

Charts diseases coronavirus https://coronavirus-world-map.net/statistics-in-panama.html

Всегда свежачок у нас !!!

(DanialNiz, 27. 5. 2020 14:54)

Ни один современный смартфон не обходится без интересных игрушек. Что касается “зеленого робота”, игры на Андроид настолько разнообразны, что выбрать желаемое бывает сложно. Но это не проблема ведь скачать игры для Андроид бесплатно можно на сайте PDALIFE.ru и попробовать понравившуюся, будь то захватывающий экшен, красивая головоломка или интересная аркада, и уже потом решить, какие игры по вкусу конкретно вам, и “по зубам” вашему смартфону.



https://androidsigra.ru/igry/ekshen

Доброй ночи дорогой человек!

(RobertApord, 10. 5. 2020 15:51)


Classifieds - Free Classified Ads Online. Their selection of ad posts covers everything imaginable;
all subdivided into easily recognisable categories like, local places, community, buy/sell/trade,
automotive, musician, rentals, real estate, jobs, dating, adult and services.
https://gorczany.com
ключи: classified, advertising cars, flats and houses, services, pets, furniture, merchandise, job
https://gorczany.com

xqbsiuvyhhhs

(orwpllpe, 2. 5. 2020 23:19)

how should we take viagra https://genviagraget.com/ coupons for viagra 100mg generika viagra billig concentrated watermelon juice viagra

Currency Exchange Brokers Assessment

(Brokersvoma, 5. 3. 2020 1:15)

Testimonials about Financial Brokers. https://currency-trading-brokers.com

Arhangeli.ru - онлайн-гадания в любое время

(GlebUnced, 13. 2. 2020 22:40)

Наверное, нет такого человека, который не хотел бы узнать, что его ждет. Гадание на картах Таро – проверенный способ узнать свое будущее. Не надо звонить гадалке, добираться, стоять в очереди к заветной комнате.

Если дома есть интернет, чтобы узнать свою будущую Судьбу, достаточно посетить сайт https://arhangeli.ru Гадания проводятся не только на Таро, но и на цыганских, игровых и картах Ангелов. Для тех, кто не понимает расклад, есть подробные описания комбинаций карт, которые выбираются самостоятельно.

Есть способы гадания на бумаге, монете, лепестках роз. Старинные восточные гадания Ицзин, Ошо Дзен Таро раскроют тайну будущих отношений, оракул Симболон поведает о дне сегодняшнем. Всего несколько кликов и на мониторе предстанет все то, что было, будет, свершится в будущем.

Monecy. Chytré investice pro vaši budoucnost.

(monecy, 11. 2. 2020 13:43)

Historicky, nemovitostmi se ukázala být jedním z nejlepších-provádění investičních tříd.Jako realitní investoři sami, strávili jsme let investovat přes tradiční přístup, jen aby viděl, kolik zisků z těchto investic spolknou neefektivita, zbytečné režijní náklady, a prostředníků, kteří přidali malou hodnotu.Dost starý způsob, jak dělat věci, začali jsme Monecy s jednoduchá myšlenka používat technologii, aby nově definovat, jak lidé investovali do nemovitostí — snížení nákladů, zlepšení kvality a rozšíření přístupu.Čelili jsme spravedlivému podílu skeptiků, včetně profesionálů z průmyslu, kteří nám řekli, že náš nápad je nemožný.
Ukázalo se, že se mýlili.Myšlenka je jednoduchá, ale silná.
Take a high quality investment class and make it available to anyone through one simple, efficient, and transparent platform. V Monecy klademe investory na první místo, tečka.Vítejte v budoucnosti investování!
https://clck.ru/M8KCo

GunsBet Casino (ГансБет Казино)

(RonaldLonry, 31. 1. 2020 1:35)

GunsBet Casino (ГансБет Казино) https://gunsbet.xyz/ Официальный сайт играть онлайн бесплатно или на деньги

Как приобрести электронный ключ

(WillieCrobE, 24. 1. 2020 14:11)

Interesting offer

(Joseph Pieni, 29. 12. 2019 20:36)

As a rule, having asked a question of installation of a ladder in the house, owners don't assume that the ladder and its protection are two absolutely different products. Well, if the same company, like us, is engaged in the arrangement of turnkey facilities and can offer to make a ladder and metal fences on it in one set, but in practice it is rare. Therefore, before any owner of the stairs in the house the question arises: how to make it safe, we guarantee the best conditions for cooperation thanks to our own production, high potential design office and focus on long-term mutually beneficial partnership. Here you can buy not only standard fencing for stairs, but also design, made to order and is amazingly cheap. New construction technologies, developing rapidly, allow to use light, modern, reliable and weightless structures. Stair railings made of stainless steel are such that the price thereof is acceptable. Railings made of reliable material: an important structural element, part of the design of the building, the guarantors of safety and easy descent and ascent the stairs. Protections for ladders which are offered by our company differ in reliability, resistance to various aggressive influences and faultless appearance. In addition, their manufacture takes into account all kinds of standards and requirements relevant to this group of products. It is difficult to imagine a building in which there will be no stair railings, the presence of which increases the convenience, safety when moving. Note that today for the manufacture of construction offers a large selection of elements with which it is possible to quickly perform the installation of the structure, which for many years will last without losing the original qualities. Manufacturing and installation of stainless steel stairs is inexpensive compared to designs from other materials with equal quality characteristics. However, stainless steel is much more popular material-it is easy to handle, combine with other materials, install and care for the finished product

Bob Casino

(AlbertoDowly, 29. 12. 2019 16:50)

Боб казино официальный сайт - https://bob-casino.xyz/

Интересное предложение

(Dames coido, 10. 10. 2019 0:03)

Depending on the layout of the house and the wishes of the customer to the design can be used marching, slanting, screw, combined and other types of glass stairs. Floating is a relatively simple type of stairs straight or curved designs, the essential element of which is the presence of the inclined series of steps and connecting them stairs (respectively rectangular or semicircular shape). The most common type of stairway has a slope of 30-45°. In such a ladder, the biomechanics of a person who moves up or down it is taken into account as much as possible. The advantage of the design of the flight stairs-the maximum strength with a minimum number of connections. For attaching stairs to the Bolza is used the same type of hinged plates boltov that is a metal fastener, which is used for sequential mounting steps. Stairs can be straight or winder. This type of ladder design allows you to make the mount almost invisible in connection with what has gained great popularity among designers. But, despite the "visual lightness", these stairs are able to withstand heavy loads, in particular, in cases where the design of the stairs is enhanced by a combination with a braid, bowstring or wall mount. In terms of design and construction, the combined staircases are characterized by a free spatial configuration, in which the elements of the staircases are combined with various spiral (screw) structures. Most modular and small stairs are also combined. Combined glass stairs-a vivid example of architectural construction in the style of "eclecticism" - the direction in which an arbitrary combination of styles, designs and materials is used. They are original engineering and artistic solutions. To perform such complex work requires the joint work of the architect and designer and, of course, a high level of professionalism of the installation team

УКП-66

(RubenSap, 27. 9. 2019 18:05)

Эфирные масла и... - выглядеть моложе своих лет на английском

(AllenKit, 24. 9. 2019 0:23)


Жаль, чем угостить не знал this

Они оба чувствуют себя настолько хорошо, что затеяли новое дело, открыв оздоровительный курорт. "Было время, когда Пол вообще ничем не хотел заниматься. Он говорил: "Я....
гормон роста в таблетках купить украина" b-a-d.ru/hgh/scientific-novital.html

заказ калибровка прошивок ЭБУ автомобилей

(Alvarobat, 24. 8. 2019 2:34)

Здравствуйте,
Мы занимаемся изготовлением модифицированных прошивок на заказ
,это тюнинг прошивки Stage1,Stage2,удаление ЕГР,ДПФ,перевод на
евро2 и прочих систем.
ролик на ютуб про нас https://youtu.be/f-6RKYIEueY

для Вас мы работаем ЕЖЕДНЕВНО!

заказ калибровки прошивки производится через email
max.autoteams@ya.ru
в заказе обязательно указываем:
Тех. задание!
1. Марка авто:
2. Модель:
3. Объём мотора:
4. Коробка (Мт/Ат):
5. Какой ЭБУ:
6. Чем читали:
7. Задание (тюн/e0/е2/EGR/DPF/Adblue/evap/SAP/TVA/TVS/либо другое):
8. прикрепляем файл стоковой,оригинальной прошивки


Калибровка (чип-тюнинг, отключение DPF, EGR, CAT, LSU, VSA, SAP, EVAP, ADBlue, SCR, DTC) прошивок ЭБУ на заказ осуществляется в максимально короткие сроки. Все заказы направляйте на почту max.autoteams@ya.ru"

Оформить кредит онлайн

(Davidexhattamn, 19. 8. 2019 15:47)

<b>Лучшие кредитные карты в банках с процентными ставками от 0% годовых, а также кэшбэком и бонусами до 70%</b>

<b>
https://kreditonline.website/ - альфа банк оформить кредит наличными онлайн</b>


1 | 2 | 3 | 4 | 5

následující »