<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/getting-data-from-pdfs-using-the-pdftools-package/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.brodrigues.co/blog/2018-06-10-scraping_pdfs/"> Econometrics and Free Software</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>It is often the case that data is trapped inside pdfs, but thankfully there are ways to extract<br>
it from the pdfs. A very nice package for this task is<br>
<code>pdftools</code> (<a rel="nofollow" href="https://github.com/ropensci/pdftools" target="_blank">Github link</a>)<br>
and this blog post will describe some basic functionality from that package.</p>
<p>First, let’s find some pdfs that contain interesting data. For this post, I’m using the diabetes<br>
country profiles from the World Health Organization. You can find them <a rel="nofollow" href="http://www.who.int/diabetes/country-profiles/en/#U" target="_blank">here</a>.<br>
If you open one of these pdfs, you are going to see this:</p>
<div>
<p><a rel="nofollow" href="http://www.who.int/diabetes/country-profiles/lux_en.pdf?ua=1" target="_blank"><br>
<img src="https://i2.wp.com/www.brodrigues.co/blog/2018-06-10-scraping_pdfs/img/diabetes_lux.png?w=450" data-recalc-dims="1"></a></p>
</div>
<p>I’m interested in this table here in the middle:</p>
<div>
<p><a rel="nofollow" href="http://www.who.int/diabetes/country-profiles/lux_en.pdf?ua=1" target="_blank"><br>
<img src="https://i2.wp.com/www.brodrigues.co/blog/2018-06-10-scraping_pdfs/img/diabetes_table.png?w=450" data-recalc-dims="1"></a></p>
</div>
<p>I want to get the data from different countries, put it all into a nice data frame and make a<br>
simple plot.</p>
<p>Let’s first start by loading the needed packages:</p>
<pre><code>library(&quot;pdftools&quot;)
library(&quot;glue&quot;)
library(&quot;tidyverse&quot;)</code></pre>
<pre><code>## ── Attaching packages ────────────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──</code></pre>
<pre><code>## ✔ ggplot2 2.2.1     ✔ purrr   0.2.5
## ✔ tibble  1.4.2     ✔ dplyr   0.7.5
## ✔ tidyr   0.8.1     ✔ stringr 1.3.1
## ✔ readr   1.1.1     ✔ forcats 0.3.0</code></pre>
<pre><code>## ── Conflicts ───────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::collapse() masks glue::collapse()
## ✖ dplyr::filter()   masks stats::filter()
## ✖ dplyr::lag()      masks stats::lag()</code></pre>
<pre><code>library(&quot;ggthemes&quot;)

country &lt;- c(&quot;lux&quot;, &quot;fra&quot;, &quot;deu&quot;, &quot;usa&quot;, &quot;prt&quot;, &quot;gbr&quot;)

url &lt;- &quot;http://www.who.int/diabetes/country-profiles/{country}_en.pdf?ua=1&quot;</code></pre>
<p>The first 4 lines load the needed packages for this exercise: <code>pdftools</code> is the package that I<br>
described in the beginning of the post, <code>glue</code> is optional but offers a nice alternative to the<br>
<code>paste()</code> and <code>paste0()</code> functions. Take a closer look at the url: you’ll see that I wrote <code>{country}</code>.<br>
This is not in the original links; the original links look like this (for example for the USA):</p>
<pre><code>&quot;http://www.who.int/diabetes/country-profiles/usa_en.pdf?ua=1&quot;</code></pre>
<p>So because I’m interested in several countries, I created a vector with the country codes<br>
of the countries I’m interested in. Now, using the <code>glue()</code> function, something magical happens:</p>
<pre><code>(urls &lt;- glue(url))</code></pre>
<pre><code>## http://www.who.int/diabetes/country-profiles/lux_en.pdf?ua=1
## http://www.who.int/diabetes/country-profiles/fra_en.pdf?ua=1
## http://www.who.int/diabetes/country-profiles/deu_en.pdf?ua=1
## http://www.who.int/diabetes/country-profiles/usa_en.pdf?ua=1
## http://www.who.int/diabetes/country-profiles/prt_en.pdf?ua=1
## http://www.who.int/diabetes/country-profiles/gbr_en.pdf?ua=1</code></pre>
<p>This created a vector with all the links where <code>{country}</code> is replaced by each of the codes<br>
contained in the variable <code>country</code>.</p>
<p>I use the same trick to create the names of the pdfs that I will download:</p>
<pre><code>pdf_names &lt;- glue(&quot;report_{country}.pdf&quot;)</code></pre>
<p>And now I can download them:</p>
<pre><code>walk2(urls, pdf_names, download.file, mode = &quot;wb&quot;)</code></pre>
<p><code>walk2()</code> is a function from the <code>purrr</code> package that is similar to <code>map2()</code>. You could use <code>map2()</code><br>
for this, but <code>walk2()</code> is cleaner here, because <code>dowload.file()</code> is a function with a so-called<br>
side effect; it downloads files. <code>map2()</code> is used for functions without side effects.</p>
<p>Now, I can finally use the <code>pdf_text()</code> function from the <code>pdftools</code> function to get the text<br>
from the pdfs:</p>
<pre><code>raw_text &lt;- map(pdf_names, pdf_text)</code></pre>
<p><code>raw_text</code> is a list of where each element is the text from one of the pdfs. Let’s take a look:</p>
<pre><code>str(raw_text)</code></pre>
<pre><code>## List of 6
##  $ : chr &quot;Luxembourg                                                                                                     &quot;| __truncated__
##  $ : chr &quot;France                                                                                                         &quot;| __truncated__
##  $ : chr &quot;Germany                                                                                                        &quot;| __truncated__
##  $ : chr &quot;United States Of America                                                                                       &quot;| __truncated__
##  $ : chr &quot;Portugal                                                                                                       &quot;| __truncated__
##  $ : chr &quot;United Kingdom                                                                                                 &quot;| __truncated__</code></pre>
<p>Let’s take a look at one of these elements, which is nothing but a very long character:</p>
<pre><code>raw_text[[1]]</code></pre>
<pre><code>## [1] &quot;Luxembourg                                                                                                                                          Total population: 567 000\n                                                                                                                                                         Income group: High\nMortality\nNumber of diabetes deaths                                                                     Number of deaths attributable to high blood glucose\n                                                                     males         females                                                            males       females\nages 30–69                                                           &lt;100            &lt;100     ages 30–69                                              &lt;100          &lt;100\nages 70+                                                             &lt;100            &lt;100     ages 70+                                                &lt;100          &lt;100\nProportional mortality (% of total deaths, all ages)                                          Trends in age-standardized prevalence of diabetes\n                    Communicable,\n                   maternal, perinatal              Injuries                                                    35%\n                    and nutritional                   6%                     Cardiovascular\n                      conditions                                               diseases\n                          6%                                                      33%\n                                                                                                                30%\n                                                                                                                25%\n                                                                                              % of population\n               Other NCDs\n                  16%                                                                                           20%\n                                     No data available                                                          15%           No data available\n              Diabetes                                                                                          10%\n                 2%\n                                                                                                                5%\n                   Respiratory\n                    diseases\n                       6%                                                                                       0%\n                                                           Cancers\n                                                            31%\n                                                                                                                                  males     females\nPrevalence of diabetes and related risk factors\n                                                                                                                      males               females               total\nDiabetes                                                                                                              8.3%                 5.3%                 6.8%\nOverweight                                                                                                            70.7%               51.5%                61.0%\nObesity                                                                                                               28.3%               21.3%                24.8%\nPhysical inactivity                                                                                                   28.2%               31.7%                30.0%\nNational response to diabetes\nPolicies, guidelines and monitoring\nOperational policy/strategy/action plan for diabetes                                                                                                ND\nOperational policy/strategy/action plan to reduce overweight and obesity                                                                            ND\nOperational policy/strategy/action plan to reduce physical inactivity                                                                               ND\nEvidence-based national diabetes guidelines/protocols/standards                                                                                     ND\nStandard criteria for referral of patients from primary care to higher level of care                                                                ND\nDiabetes registry                                                                                                                                   ND\nRecent national risk factor survey in which blood glucose was measured                                                                              ND\nAvailability of medicines, basic technologies and procedures in the public health sector\nMedicines in primary care facilities                                                          Basic technologies in primary care facilities\nInsulin                                                                               ND      Blood glucose measurement                                             ND\nMetformin                                                                             ND      Oral glucose tolerance test                                           ND\nSulphonylurea                                                                         ND      HbA1c test                                                            ND\nProcedures                                                                                    Dilated fundus examination                                            ND\nRetinal photocoagulation                                                              ND      Foot vibration perception by tuning fork                              ND\nRenal replacement therapy by dialysis                                                 ND      Foot vascular status by Doppler                                       ND\nRenal replacement therapy by transplantation                                          ND      Urine strips for glucose and ketone measurement                       ND\nND = country did not respond to country capacity survey\n〇 = not generally available   ● = generally available\nWorld Health Organization – Diabetes country profiles, 2016.\n&quot;</code></pre>
<p>As you can see, this is a very long character string with some line breaks (the <code>&quot;\n&quot;</code> character).<br>
So first, we need to split this string into a character vector by the <code>&quot;\n&quot;</code> character. Also, it might<br>
be difficult to see, but the table starts at the line with the following string:<br>
<code>&quot;Prevalence of diabetes&quot;</code> and ends with <code>&quot;National response to diabetes&quot;</code>. Also, we need to get<br>
the name of the country from the text and add it as a column. As you can see, a whole lot<br>
of operations are needed, so what I do is put all these operations into a function that I will apply<br>
to each element of <code>raw_text</code>:</p>
<pre><code>clean_table &lt;- function(table){
    table &lt;- str_split(table, &quot;\n&quot;, simplify = TRUE)
    country_name &lt;- table[1, 1] %>% 
        stringr::str_squish() %>% 
        stringr::str_extract(&quot;.+?(?=\\sTotal)&quot;)
    table_start &lt;- stringr::str_which(table, &quot;Prevalence of diabetes&quot;)
    table_end &lt;- stringr::str_which(table, &quot;National response to diabetes&quot;)
    table &lt;- table[1, (table_start +1 ):(table_end - 1)]
    table &lt;- str_replace_all(table, &quot;\\s{2,}&quot;, &quot;|&quot;)
    text_con &lt;- textConnection(table)
    data_table &lt;- read.csv(text_con, sep = &quot;|&quot;)
    colnames(data_table) &lt;- c(&quot;Condition&quot;, &quot;Males&quot;, &quot;Females&quot;, &quot;Total&quot;)
    dplyr::mutate(data_table, Country = country_name)
}</code></pre>
<p>I advise you to go through all these operations and understand what each does. However, I will<br>
describe some of the lines, such as this one:</p>
<pre><code>stringr::str_extract(&quot;.+?(?=\\sTotal)&quot;)</code></pre>
<p>This uses a very bizarre looking regular expression: <code>&quot;.+?(?=\\sTotal)&quot;</code>. This extracts everything<br>
before a space, followed by the string <code>&quot;Total&quot;</code>. This is because the first line, the one that contains<br>
the name of the country looks like this: <code>&quot;Luxembourg Total population: 567 000\n&quot;</code>. So everything<br>
before a space followed by the word <code>&quot;Total&quot;</code> is the country name. Then there’s these lines:</p>
<pre><code>table &lt;- str_replace_all(table, &quot;\\s{2,}&quot;, &quot;|&quot;)
text_con &lt;- textConnection(table)
data_table &lt;- read.csv(text_con, sep = &quot;|&quot;)</code></pre>
<p>The first lines replaces 2 spaces or more (“<code>\\s{2,}</code>”) with <code>&quot;|&quot;</code>. The reason I do this is because<br>
then I can read the table back into R as a data frame by specifying the separator as the “|” character.<br>
On the second line, I define <code>table</code> as a text connection, that I can then read back into R using<br>
<code>read.csv()</code>. On the second to the last line I change the column names and then I add a column<br>
called <code>&quot;Country&quot;</code> to the data frame.</p>
<p>Now, I can map this useful function to the list of raw text extracted from the pdfs:</p>
<pre><code>diabetes &lt;- map_df(raw_text, clean_table) %>% 
    gather(Sex, Share, Males, Females, Total) %>% 
    mutate(Share = as.numeric(str_extract(Share, &quot;\\d{1,}\\.\\d{1,}&quot;)))</code></pre>
<p>I reshape the data with the <code>gather()</code> function (see what the data looks like before and after<br>
reshaping). I then convert the <code>&quot;Share&quot;</code> column into a numeric (it goes from something that looks<br>
like <code>&quot;12.3 %&quot;</code> into <code>12.3</code>) and then I can create a nice plot. But first let’s take a loot at<br>
the data:</p>
<pre><code>diabetes</code></pre>
<pre><code>##              Condition                  Country     Sex Share
## 1             Diabetes               Luxembourg   Males   8.3
## 2           Overweight               Luxembourg   Males  70.7
## 3              Obesity               Luxembourg   Males  28.3
## 4  Physical inactivity               Luxembourg   Males  28.2
## 5             Diabetes                   France   Males   9.5
## 6           Overweight                   France   Males  69.9
## 7              Obesity                   France   Males  25.3
## 8  Physical inactivity                   France   Males  21.2
## 9             Diabetes                  Germany   Males   8.4
## 10          Overweight                  Germany   Males  67.0
## 11             Obesity                  Germany   Males  24.1
## 12 Physical inactivity                  Germany   Males  20.1
## 13            Diabetes United States Of America   Males   9.8
## 14          Overweight United States Of America   Males  74.1
## 15             Obesity United States Of America   Males  33.7
## 16 Physical inactivity United States Of America   Males  27.6
## 17            Diabetes                 Portugal   Males  10.7
## 18          Overweight                 Portugal   Males  65.0
## 19             Obesity                 Portugal   Males  21.4
## 20 Physical inactivity                 Portugal   Males  33.5
## 21            Diabetes           United Kingdom   Males   8.4
## 22          Overweight           United Kingdom   Males  71.1
## 23             Obesity           United Kingdom   Males  28.5
## 24 Physical inactivity           United Kingdom   Males  35.4
## 25            Diabetes               Luxembourg Females   5.3
## 26          Overweight               Luxembourg Females  51.5
## 27             Obesity               Luxembourg Females  21.3
## 28 Physical inactivity               Luxembourg Females  31.7
## 29            Diabetes                   France Females   6.6
## 30          Overweight                   France Females  58.6
## 31             Obesity                   France Females  26.1
## 32 Physical inactivity                   France Females  31.2
## 33            Diabetes                  Germany Females   6.4
## 34          Overweight                  Germany Females  52.7
## 35             Obesity                  Germany Females  21.4
## 36 Physical inactivity                  Germany Females  26.5
## 37            Diabetes United States Of America Females   8.3
## 38          Overweight United States Of America Females  65.3
## 39             Obesity United States Of America Females  36.3
## 40 Physical inactivity United States Of America Females  42.1
## 41            Diabetes                 Portugal Females   7.8
## 42          Overweight                 Portugal Females  55.0
## 43             Obesity                 Portugal Females  22.8
## 44 Physical inactivity                 Portugal Females  40.8
## 45            Diabetes           United Kingdom Females   6.9
## 46          Overweight           United Kingdom Females  62.4
## 47             Obesity           United Kingdom Females  31.1
## 48 Physical inactivity           United Kingdom Females  44.3
## 49            Diabetes               Luxembourg   Total   6.8
## 50          Overweight               Luxembourg   Total  61.0
## 51             Obesity               Luxembourg   Total  24.8
## 52 Physical inactivity               Luxembourg   Total  30.0
## 53            Diabetes                   France   Total   8.0
## 54          Overweight                   France   Total  64.1
## 55             Obesity                   France   Total  25.7
## 56 Physical inactivity                   France   Total  26.4
## 57            Diabetes                  Germany   Total   7.4
## 58          Overweight                  Germany   Total  59.7
## 59             Obesity                  Germany   Total  22.7
## 60 Physical inactivity                  Germany   Total  23.4
## 61            Diabetes United States Of America   Total   9.1
## 62          Overweight United States Of America   Total  69.6
## 63             Obesity United States Of America   Total  35.0
## 64 Physical inactivity United States Of America   Total  35.0
## 65            Diabetes                 Portugal   Total   9.2
## 66          Overweight                 Portugal   Total  59.8
## 67             Obesity                 Portugal   Total  22.1
## 68 Physical inactivity                 Portugal   Total  37.3
## 69            Diabetes           United Kingdom   Total   7.7
## 70          Overweight           United Kingdom   Total  66.7
## 71             Obesity           United Kingdom   Total  29.8
## 72 Physical inactivity           United Kingdom   Total  40.0</code></pre>
<p>Now let’s go for the plot:</p>
<pre><code>ggplot(diabetes) + theme_fivethirtyeight() + scale_fill_hc() +
    geom_bar(aes(y = Share, x = Sex, fill = Country), 
             stat = &quot;identity&quot;, position = &quot;dodge&quot;) +
    facet_wrap(~Condition)</code></pre>
<p><img src="https://i2.wp.com/www.brodrigues.co/blog/2018-06-10-scraping_pdfs/blog/2018-06-10-scraping_pdfs_files/figure-html/unnamed-chunk-11-1.png?w=450" data-recalc-dims="1"></p>
<p>That was a whole lot of work for such a simple plot!</p>
<p>If you found this blog post useful, you might want to follow me on <a rel="nofollow" href="https://www.twitter.com/brodriguesco" target="_blank">twitter</a><br>
for blog post updates.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.brodrigues.co/blog/2018-06-10-scraping_pdfs/"> Econometrics and Free Software</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/8ntLQKrkMME" height="1"></a></div>